Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A = b || "foo"; complains that 'b' is undefined and does not assign a to "foo". What am I missing?

Tags:

javascript

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?

like image 527
Daniel Williams Avatar asked Apr 29 '14 14:04

Daniel Williams


2 Answers

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".

like image 187
Denys Séguret Avatar answered Oct 21 '22 03:10

Denys Séguret


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";
};
like image 21
freakish Avatar answered Oct 21 '22 04:10

freakish