0

I recently had to deal with some javascript and came across this code:

name: function(arg){
            //...
            var arg = arg || new Object();
            //...
}

TBH, I'm not quite fit in js, but as far as I know, this means that if arg is not defined, arg will be new Object(); My question now is, how does js know that this isn't considered a boolean interpretation? Or how excatly does this comparison work?

Like, javascript does have dynamic data types, so I would have assumed if arg was a boolean, (and if I'm not wrong, the boolean value of new Object(); is always true) arg would be true after running the function, no matter the previous value of arg was. However, I tested that, using various parameters (and again, I'm new to js) and the results are quite strange to me:

Using:

function name(arg) {
    var arg = arg || new Object();
    return arg;
}

Results:

name() = [object Object]
name(1) = 1
name(true) = true
name(false) = [object Object]
name('true') = true
name('false') = false
name(null) = [object Object]

I would have expected these results, except for name(false) = [object Object]. What's the reason for that result? I couldn't really find a satisfying answer.

Regards, Simon

Zaheylu
  • 313
  • 2
  • 9
  • `name (false)` passes `false` (boolean) as a parameter. However, this kind of OR that you setted up can be also seen as a sort of "if" statement, which works like: "if `exp1` is false, then `exp2`". Therefore, passing false as the first parameters executes `exp2`, which is your object. when you pass 'false', instead, you're passing a string, which is an object, therefore it will evaluate to TRUE and won't execute exp2 – briosheje Mar 05 '15 at 11:35

1 Answers1

1

...this means that if arg is not defined, arg will be new Object();

Not quite: It means that if arg has a falsey value, then assign new Object() to arg.

The || operator works like this: It evaluates the left-hand operand and if that value is truthy, the result of the operation is that value; otherwise, it evaluates the right-hand operand and results in that value.

So what are "falsey" and "truthy"? Falsey values are undefined, null, 0, "", NaN, and of course, false. Truthy values are all others.

More in this article on my blog.

The && operator is similarly powerful, in a somewhat converse way: It evalutes the left-hand operand and if that value is falsey, the result of the operation is that value; otherwise it evalutes the right-hand operand and the result is that value. So a = b && b.foo; will assign a the value of b if it's falsey (null, undefined, etc.) or the value of b.foo if not.

My question now is, how does js know that this isn't considered a boolean interpretation?

Because that's how it's defined in the specification. JavaScript's || and && are different from, say, Java's which always result in a boolean. It's by design, and very powerful.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875