HTML and CSS Reference
In-Depth Information
The first parameter for both functions is the string you want to convert to a number. Note that parseInt
automatically truncates anything after the decimal point rather than rounding.
parseInt also takes an optional second parameter, which is the radix, or base of the number system being
converted to. The default is the standard base-10 number system.
It's worth pointing out the reverse process, converting a number to a string. The primary way to do this is to call
String(value), where value is what you want converted to a string.
Equality Checking
One of the greatest challenges for new JavaScript developers is, without a doubt. equality checking. Thankfully, the
key to avoiding getting tripped up can be summed up very easily:
Always use === and !== to do equality checking rather than == and !=.
But, why must you do that? What's the deal with this === nonsense, and why are there two different equality
The answer has to do with our friend automatic type coercion. == and != will automatically convert values
to different types before comparing them for equality. The === and !== operators do not and will return false for
different types.
However, what are the rules for how == converts types?
Comparing numbers and strings will always convert the strings to numbers.
null and undefined will always equal each other.
Comparing booleans to any other type will always cause the booleans to be converted
to numbers.
Comparing numbers or strings to objects will always cause the numbers or strings to be
converted to objects.
false .
Once the types have been converted, the comparison continues the same as with ===. Numbers and booleans
are compared by value, and strings, by identical characters. null and undefined equal each other and nothing else,
and objects must reference the same object.
Now that you know how == works, the earlier advice never to use it can be relaxed, at least a little bit. == can be
useful, but you must be absolutely sure you know what you're doing.
Any other type comparisons are automatically
Using various types in conditional statements is similarly problematic. Because of type coercion, you can use any type
in a conditional, and that type is converted to a boolean.
The rules for converting other types to booleans are actually relatively straightforward:
undefined and null are always false .
Booleans are just treated as booleans (obviously).
false if they equal 0 or NaN ; otherwise, they're true .
Numbers are
true , except for the empty string "" , which is false .
Strings are
true .
Objects are always
Search WWH ::

Custom Search