In my JavaScript code, and in Chrome dev tools I write:
a = b || "foo";
And get this error:
ReferenceError: b is not defined
And a is not set to "foo". I know this is a valid pattern in JavaScript. What am I missing?
Your pattern is OK if the value of b
is undefined
.
If the variable b
might be not defined, it's an error to try to read it so it's a little more complicated :
a = typeof b!=="undefined" ? b : "foo";
Be careful with b||something
even when you know the variable is defined (which is the most common case) : Most often you want to provide a default value to replace undefined
, not prevent the caller to pass 0
or ""
so it's usually safer to do b!==undefined ? b : "foo"
.
That is not a valid pattern in JavaScript. It is only valid in a context where b
exists, for example
function test(b) {
var a = b || "foo";
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With