1 + undefined = ?
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
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With