Question

I am learning JavaScript and was asked this question, can anyone help? What do the following Javascript statements return and why?

parseInt("07"); parseInt("09"); parseInt("010");

"1" + 2 + 3;

"1" == 1; "1" === 1; "1" == true; "1" === false;

Was it helpful?

Solution

Fire up a Development console (like the one in the Chrome Developer Tools or Firebug) and type in the statements, you'll get the results:

parseInt('07'); -> 7
parseInt('09'); -> 0
parseInt('010'); -> 8

This happens, because parseInt tries to determine the right base of the number contained in the string you're passing. These numbers are starting with 0, so JavaScript assumes you're passing "octal" - values. 09 for example doesn't exist there, so it returns 0. You can easily go around this problem by passing a second parameter to parseInt (called the "radix")

So, if you want decimal numbers, which will be the case most of the times, you write:

parseInt('09', 10);


"1" + 2 + 3;

will return the string "123", because JavaScript automatically converts type behind the scenes. Adding numbers to a string will just convert them and concatenate them.

"1" == 1; "1" === 1; "1" == true; "1" === false;

Here we have the two different operators for comparing. == will compare only value, === will compare value and type. It is considered a good practice to use === most of the time, unless you're really sure you want to use ==.

Your first statement will return true, types are converted behind the scenes and the value is the same, your second statement will return false, because the types are not converted and you are comparing String against Number. The third will return true, because "1" is considered as truthy value. The fourth will of course return false, because of this.

OTHER TIPS

parseInt("07"); parseInt("09"); parseInt("010");

7,
0, (invalid)
8

respectively. This is because 0 in front designated octal number. And octal number can just contain characters from 0-7. 9 is invalid.

"1" + 2 + 3;

123 (string)

"1" == 1; "1" === 1; "1" == true; "1" === false;

true
false
true
false
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top