What the Heck is the ‘+’ for?

I came across the following that someone had added to some code I was working on:

incidentId = +idValue;

I initially thought this was something to do with jQuery (because of the single initial punctuation). Remember, this blog’s goal is to document my experiences in learning how to do stuff in JavaScript, not to make me look smart.

It turns out that it’s the same old unary operator we’re used to seeing in more ‘normal’ (less flexible) languages. What this tells the runtime is to treat the value in idValue as a number. Often, we are passing around strings which contain numbers and JavaScript is good at converting stuff for us. If we were to pass idValue in the above code as a string “1”, then the following

idValue + 2

might be calculated as “12” depending on the context, whereas:

+idValue + 2

would always be the number 3.


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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s