Skip navigation

Let us assume this syntax

var kk=+"2";

Is it valid? Yes, it is. To confirm, check this

alert(kk+2);  //4

will alerts you with 4. So what does + sign before a string doing? The answer is + sign before a string converts the string type into a number type. Want a proof?

typeof(kk);  // number

Interesting na… check some other related alerts below

typeof(2); // number
typeof("2"); // string
typeof(+"2"); // number
alert(+"2"+2);  // 4
alert("2"+2);  // 22
var k = +"raja"; // :-)
typeof(k);  // number
alert(k);  // NaN (is a number)

JavaScript is cute !!!

Update: Also read this wonderful article written long back.

Advertisements

2 Comments

  1. Rajakvk, the “=” operator is for assignment. The combination “+=” is for situations where you want to combine/add to values together. For instance, var x = 2; var y = 3; x += y; would at the end add the value of y to x. With strings, var x = “This is”; var y = ” some text”; x += y; will result in y being “This is some text”
    Putting a number in quotes converts it to a string. Putting a math operator directly before or after a number, particularly “-” or “+” is used for decreasing or increasing its value by 1:
    for (var i = 0; i < 100; i++)

    • Not exactly.

      Should you place a ‘+’ between two strings, they’ll concatenate. So only an unary plus does convert string to number


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: