In Javascript that num = + thenum || does false mean?
I learned JavaScript myself by reading a book. I cannot understand one of the code
var thenum = document.getElementById("sr_num").value;
thenum = +thenum || false
The last line is never explained in the book. I couldn't figure out what it was about. Anyone who could explain this would love me very much. Thank.
source to share
thenum = +thenum || false
- make sure that it thenum
is a valid number. If it is not, then it thenum
will be appointed false
.
+thenum
will try to convert the string value to thenum
( document.getElementById("sr_num").value
will give the string value) to a number. If it fails, it will return NaN
which is considered false. You can confirm that like this
console.log(+"All hail lelouch");
// NaN
So, if thenum
it is not a valid number, then the expression becomes
thenum = NaN || false
Since it NaN
is false, it false
will be assigned to thenum
.
Note. The only valid numeric input for which this expression will not work is 0
. Since as you type, the "0"
expression becomes
thenum = +"0" || false
= 0 || false
So thenum
it will continue to be appointed false
.
source to share
HTMLInputElement.value
returns a string. +thenum
is called the Unary plus operator and converts any value to Number
or NaN
. Since it NaN
is false, the OR ( ||
) operator will evaluate the second half of the expression by assigning false
thenum
. Another exception is that it +thenum
has a value of 0, the only number of false numbers. This would also be appropriating false
thenum
, although this does not appear to be intentional behavior. Apart from these two exceptions, since all other numbers are truthful, the second half of the OR expression will not be evaluated and a number will be assigned thenum
. The following snippets will demonstrate what is happening.
Equivalent behavior:
if(+thenum) {
thenum = +thenum;
else {
thenum = false;
}
(possibly) intended behavior:
if(isNaN(+thenum)) {
thenum = false;
} else {
thenum = +thenum;
}
Reducing the indicated (possibly) intended behavior:
thenum = (isNaN(thenum = +thenum) ? false : thenum);
Hope this helps clarify the situation.
source to share