Javascript: _ = +_;

posted in: Uncategorized | 0

Came across something interesting on Stack Overflow today. Some operators that I didn’t know existed and a reminder that an underscore is a valid variable name.

The following is valid javascript:

var _ = "1";
_ = +_;
alert(_);

The second line might seem a bit weird, but it actually does do something. _ is a string on line one, thanks to the quotes. On line two, we use the + operator to cast it to a number. So, the alert will alert the integer 1.

Here’s another one

var _ = "1";
_ = -_;
alert(_);

This one is very similar to the first example, except this one converts the string to a negative integer. The result of the alert would be the integer -1;

One more example, this time playing with booleans.

var a = true;
a = !a;
alert(a);

As you may have already guessed, the second line in this example changes true to false.

One last one that you have probably already seen, but I find incredibly useful, conditional assignment.

var a = true;
var b = (a) ? 1 : 0;
alert(b);

the alert will alert (1), since a is true. Line 2 is the equivalent of:

var a = true;
var b;
if(a)
   b = 1;
else
   b = 0;
alert(b);

Just some weird things that may or may not be useful, but I found to be interesting.

INSPIRED BY: http://stackoverflow.com/questions/15129137/what-does-mean-in-javascript

My name is Andrew McGivery. I currently work full time as an application developer at Manulife Financial in Canada. My current passion is building and leading highly engaged teams where employee happiness, learning, and growth is a priority.

Leave a Reply