Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the result of 1 + undefined

Tags:

javascript

1 + undefined = ?  
  1. first, String(undefined) get string "undefined"
  2. second, 1 + "undefined" = "1undefined"

what's wrong?

I run it in chrome console ,it return NaN.

can you pls explain the result?

I think it should be "1undefined". tks

like image 314
looping Avatar asked Feb 20 '13 10:02

looping


People also ask

What does it mean when your result is undefined?

A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value.

Can you add a number to undefined?

You should define test as 0 to begin with so that it starts out as an object of type Number . Adding numbers to undefined results in NaN (not-a-number), which won't get you anywhere.

How do you change undefined to zero?

Use the ternary operator to convert an undefined value to zero, e.g. const result = val === undefined ? 0 : val . If the value is equal to undefined , the operator returns 0 , otherwise the value is returned.

Why is undefined true?

undefined is true because undefined implicitly converts to false , and then ! negates it. Collectively, those values (and false ) are called falsy values. Anything else¹ is called a truthy value.


2 Answers

NaN is the result of a failed Number operation.

1 + undefined           // NaN
"1" + undefined         // "1undefined"
1 + "" + undefined      // "1undefined"
1 + ("" + undefined)    // "1undefined"
typeof NaN              // "number"
typeof undefined        // "undefined"
NaN === NaN             // false (it's not reflexive!)
undefined === undefined // true (it's reflexive)
NaN.toString()          // "NaN"

NaN means Not a Number where a number was expected. Any Number operation with NaN will result in NaN as well.

like image 60
Halcyon Avatar answered Oct 04 '22 08:10

Halcyon


You expect a string concatenation, but this will only happen if you have at least one string. And in your example nothing is a string. 1 is not a string and undefined is not a string.

like image 36
exebook Avatar answered Oct 02 '22 08:10

exebook