Pages

Thursday, September 12, 2013

Javascript-Typecasting-Question

What will this print

<script type="text/javascript">
alert('1'+2+4);
</script>


Ans : 124(since js typcasts everthing to string if a string is encountered)


When dealing with two numbers, the + operator adds these. When dealing with two strings, it concatenates.

3 + 5;              // 8
"hello " + "world"; // "hello world"
"3" + "5";          // "35"
 
 
When one operand is a string and the other is not, the other is converted to a string and the result is concatenated. 

"the answer is " + 42; // "the answer is 42"
"this is " + true;     // "this is true"
var a;
"a is " + a;           // "a is undefined"
 
In any other case (except for Dates) the operands are converted to numbers and the results are added.
 
1 + true;     // -> 1 + 1 -> 2
null + false; // -> 0 + 0 -> 0
 
 

No comments:

Post a Comment