Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return String vs Integer vs undefined vs null

Tags:

javascript

Why does javascript prefers to return a String over any other choices ?

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 called a non-existent array element.

However i cannot understand why does arr.item(43) returns the String ? Why not null or undefined or even 12 ?

like image 576
Pierre Avatar asked Dec 20 '11 15:12

Pierre


People also ask

What is the difference between undefined and null?

Undefined typically refers to something which has not yet been assigned a value (yet). Null refers to something which definitively has no value. In that case, I would recommend returning a null. Note that a function with no specified return value implicitly returns undefined.

What is an undefined variable in JavaScript?

In JavaScript an undefined variable is a variable that as never been declared, or never assigned a value. Let's say you declare var a; for instance, then a will be undefined, because it was never assigned any value. But if you then assign a = null; then a will now be null.

Are null and undefined primitive values in JavaScript?

Both null and undefined are primitive values. Here is a full list: All other values in JavaScript are objects (objects, functions, arrays, etc.). Interestingly enough, when using typeof to test null, it returns object:

What does undefined mean in C++?

Undefined: It means the value does not exist in the compiler. It is the global object. You can see refer to “==” vs “===” article. It means null is equal to undefined but not identical. When we define a variable to undefined then we are trying to convey that the variable does not exist .


1 Answers

Because this[x] is undefined, which is falsy, and so is null.

The || operator returns the first "truthy" value it finds, and stops its evaluation at that point.

If no "truthy" value is found, it returns the result of the last operand evaluated.

There are a total of 6 "falsey" values. They are...

  1. false
  2. undefined
  3. null
  4. ""
  5. NaN
  6. 0

Everything else is considered truthy.

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 could look at it like this:

(
  (
    (
      (this[x] || null) // return null
            /* (null */ || 'aïe') // return 'aïe' and stop evaluating
                                || 12) 
                                      || undefined);
like image 110
5 revsuser1106925 Avatar answered Sep 20 '22 03:09

5 revsuser1106925