Reputation: 21302
If the value exists do stuff, else do not:
var cookarr = document.cookie.match(/(^| )abc_contact\=([^;]*)(;|$)/);
var iscontact = cookarr[2];
var outcome = 0;
if(iscontact) {
outcome = true;
} else {
outcome = false;
}
If there is a cookie called abc_contact then the returned cookarr variable index of 2 will be the value of that cookie.
In the instance where the cookie does not exist cookarr will be null.
The variable outcome is never set, the error seems to break the flow. Uncaught TypeError: Cannot read property '2' of null
How do I tell Javascript to just set iscontact to null if there is no cookie, as opposed to throwing an error?
I recall seeing some JS in the past where a variable was set like var apples = 'bla' || 'something else';
Is that relevant here? Something like if it exists leave it else define it? Or am I on the wrong path?
Upvotes: 0
Views: 127
Reputation: 4091
Try:
var iscontact = cookarr && cookarr[2] || null;
||
can be used as JavaScript's version of a null coalesce operator. It will say, "If the value on the left is truthy, use that. Else, use the value on the right". But in this case, you don't even need ||
.
The following will work fine:
var iscontact = cookarr && cookarr[2]
The &&
check above is a shortcut to get the element of the array if the array itself exists. The values in the &&
chain (there are only two here) will be evaluated in order. If it comes across a value that evaluates as falsy, it will stop and return it. Else, it will return the last value in the chain.
In your code, if cookarr
is null (falsy) then the chain ends and iscontact
gets set to null. If cookarr
isn't null and returns a truthy value, then the chain continues to the next (and last) item in the chain, and sets iscontact
to cookarr[2]
.
To answer your question, "Why can't I just use iscontact = cookarr[2] || null":
When the JavaScript engine tries to evaluate cookarr[2]
(when cookarr
is null), it's trying to do null[2]
. In JavaScript, null
is an object
, so this notation is the same as getting the value of an object property. Since 2
is not a property of null
, it throws the error.
Upvotes: 2
Reputation: 7490
you could check the cookie first. checking that it's not undefined and that it has enough matches
var cookarr = document.cookie.match(/(^| )abc_contact\=([^;]*)(;|$)/);
if (cookarr && cookarr.length > 1){
var iscontact = cookarr[2];
var outcome = 0;
if(iscontact) {
outcome = true;
} else {
outcome = false;
}
}
Upvotes: 0