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;
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
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:
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.
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.