Return String vs Integer vs undefined vs null

Why does javascript prefer to return String in any other way?

Consider the following snippet.

 var arr = ['Hello1', 'Hello2', 'Hello3']; Array.prototype.item = function(x) { return this[x] || null || 'aïe' || 12 || undefined ; }; console.log( arr.item(43) ); // returns aïe 

I intentionally named a nonexistent array element.

However, I cannot understand why arr.item(43) returns a String ? Why not null or undefined or even 12 ?

+8
javascript
source share
6 answers

Because this[x] is undefined , which is false, and therefore null .

Operator || returns the first "true" value that it finds, and stops its evaluation at that point.

If no "true" value is found, it returns the result of evaluating the last operand.

In total, there are 6 false values. They are...

  • false
  • undefined
  • null
  • ""
  • NaN
  • 0

Everything else is considered true.

So your expression will be evaluated as ...

 // v--falsey v--truthy! return it! ((((this[x] || null) || 'aïe') || 12) || undefined); // ^--falsey ^--------^---these are not evaluated at all 

Or you can look at it like this:

 ( ( ( (this[x] || null) // return null /* (null */ || 'aïe') // return 'aïe' and stop evaluating || 12 ) || undefined ); 
+25
source share

Statement

 return this[x] || null || 'aïe' || 12 || undefined ; 

will evaluate the subexpressions from left to right and will return the first subexpression that is not evaluated as false. A nonexistent element evaluates false to undefined, and null by definition false. This leaves the string as the first non-false subexpression, so what you get.

+5
source share

Code a || b a || b roughly equivalent to a ? a : b a ? a : b , or this is a bit more verbose code:

 if (a) { result = a; } else { result = b; } 

Since || left associative expression a || b || c a || b || c a || b || c is estimated as (a || b) || c (a || b) || c .


Thus, this means that the operator || in the chain returns the first operand, which is "true", or the last element.

This function can be useful to provide default values ​​if you do not have values:

 var result = f() || g() || defaultValue; 

You can read this as: Get the result of f (). If this is a false value, try g (). If this also gives a false value, use defaultValue .

+3
source share

A string is the first legal value in a chain or. Simples.

+1
source share

Because it is ranked in order from left to right.

If you were to change this:

 return this[x] || null || 12 || 'aïe' || undefined ; 

Your answer will be 12.

+1
source share

return this[x] || null || 'aïe' || 12 || undefined return this[x] || null || 'aïe' || 12 || undefined will not return one of them. It is supposed to return the result of the expression this[x] || null || 'aïe' || 12 || undefined this[x] || null || 'aïe' || 12 || undefined this[x] || null || 'aïe' || 12 || undefined - I believe that it will return a boolean value.

0
source share

All Articles