I have found in HighStock js they have write a syntax like
n= +Number || 0
can anyone please expalin mean what does it mean?
Thanks
I have found in HighStock js they have write a syntax like
n= +Number || 0
can anyone please expalin mean what does it mean?
Thanks
Share Improve this question asked Jan 7, 2015 at 6:32 Dhaval PatelDhaval Patel 7,6016 gold badges43 silver badges71 bronze badges 1- stackoverflow./questions/5450076/… – chiliNUT Commented Jan 7, 2015 at 6:35
3 Answers
Reset to default 6This is:
n= +Number || 0;
variable n
will be assigned a value which should be typeof == number
. If number is string then +number
will be a shorthand to convert string number values to number.
So if value es as "20"
, its a String value and if you prefix it with +
sign then it will be converted to an Integer like 20
.
Here:
n= +Number || 0;
Integer 0
will be assigned if there is no value in the var Number
/or undefined.
var number = "20", nonumber;
var n = +number || 0;
$('p:eq(0)').text(n);
var o = +nonumber || 0;
$('p:eq(1)').text(o);
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p></p>
<p></p>
It means if Number
variable is not defined
or its not numeric
then assign 0
to the n
variable.
Example
Example 1>
var Number = 'test';
n= +Number || 0;
O/P:
n = 0
--------------------------------------------
Example 2>
var Number = 2;
n= +Number || 0;
O/P:
n = 2
--------------------------------------------
Example 3>
n= +Number || 0;
O/P:
n = 0
So essentially, when you have either +
or -
before a variable, (ie. +Number
), the variable gets cast to the type number. So either this is successful and a number is the output, or the casting fails and NaN
is returned (Not a Number).
Since in most browsers Number
refers to the object constructor for the type number, then the casting of it to a numerical value is not defined, and thus the result is NaN
, which JavaScript interprets as a false value. Therefore:
+Number || 0 == NaN || 0 == 0
Unless Number has been defined locally and is a number (or can be casted into a number).
The following describes how each type gets casted into a number:
// Strings
+"1.12345" = 1.12345
parseFloat("1.12345") // Equivalent to
// Boolean
+True = 1
+False = 0
Number(True) // Equivalent
// Array
+[1] = NaN
// Casting fails
// Object
+{1:1} = NaN
// Casting Fails
// Undefined
+undefined = NaN
// Casting Fails
// Null
+null = 0
Number(null) // Equivalent
// Hex encoded number
+0x00FF = 255
parseInt("0x00FF", 16) // Equivalent
// Function
+function(){} = NaN
// Casting Fails