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?
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?
Share Improve this question edited Apr 30, 2014 at 4:27 Peter O. 32.9k14 gold badges84 silver badges97 bronze badges asked Apr 29, 2014 at 14:39 Daniel WilliamsDaniel Williams 9,32416 gold badges78 silver badges117 bronze badges 6- 2 "Have I not had enough coffee?" How can we know... Do you have such feeling? Than drink some more. – nicael Commented Apr 29, 2014 at 14:41
-
var a = window.b || "foo";
.. ifb
is global variable.. – Mr_Green Commented Apr 29, 2014 at 14:47 - @Mr_Green And if the variable is in another scope ? – Denys Séguret Commented Apr 29, 2014 at 14:47
-
@dystroy may be
this.b
.. :| – Mr_Green Commented Apr 29, 2014 at 14:48 - @Mr_Green You want to thing again about this one... – Denys Séguret Commented Apr 29, 2014 at 14:50
2 Answers
Reset to default 11Your 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 plicated :
a = typeof b!=="undefined" ? b : "foo";
Be careful with b||something
even when you know the variable is defined (which is the most mon 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";
};