elrrrrrrr
elrrrrrrr

Reputation: 944

JS type conversion between string and number

I'm puzzled with the type convert in javascript .

var temp = "111"
temp = temp + 0 // temp is "1110" now 
temp = temp - 0 // temp is number , 111 

temp = "1110" - 0 // temp is number 1110

I'm curious what causes such differences in two ways .

Sorry , I forgot the assignment led to abnormal results .

Upvotes: 1

Views: 119

Answers (3)

Wenbing Li
Wenbing Li

Reputation: 12982

From ECMAScript Language Specification. For Addition operator:

7.If Type(lprim) is String or Type(rprim) is String, then Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)

8.Return the result of applying the addition operation to ToNumber(lprim) and ToNumber(rprim).

This means + operator will try String firstly if one of them is String. Otherwise, it will apply number addition by converting them into number.

For Subtraction Operator :

5.Let lnum be ToNumber(lval).

6.Let rnum be ToNumber(rval).

7.Return the result of applying the subtraction operation to lnum and rnum

It means - operator will always convert to number and apply number subtraction operation.

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 817208

I doubt that

temp = temp - 0 // temp is number , 111 

yields the result you mentioned there. See http://jsbin.com/faquvobo/1/edit?js,output

You have an observation error (maybe you actually used temp = 0 + temp;).


General explanation:

The + operator is overloaded and the - operator isn't.

If you use the + operator and one operand is a string, the operand is converted to a string and string concatenation is performed (instead of addition).

The - operator is only defined for numbers, so both operands are converted to numbers first and subtraction is performed.

Upvotes: 1

Ferdi265
Ferdi265

Reputation: 2969

in javascript, the + operator performs typecasting to string if either of the operands is not a number, while the - operator always casts to number.

so your code will look like this after typecasting:

var temp = "111";

//before cast and variable evaluation
var temp2 = temp + 0;
//after cast and variable evaluation
var temp2 = "111" + "0"; // evaluates to string "1110" => string concatenate
//temp2 is string "1110"
//before cast and variable evaluation
temp2 = temp2 - 0;
//after cast and variable evaluation
temp2 = 1110 - 0; //evaluates to number 1110 => number subtraction
//temp2 is number 1110

//before cast and variable evaluation
var temp3 = "1110" - 0;
//after cast and variable evaluation
var temp3 = 1110 - 0; // evaluates to number 1110 => number subtraction
//temp3 is number 1110

Upvotes: 1

Related Questions