Operations on Numbers & Strings

In JavaScript, numbers and strings will occasionally behave in ways you might not expect.

Example 2.8: Addition vs. concatenation
var foo = 1;
var bar = ‘2’;

console.log(foo + bar); // 12. uh oh

Example 2.9: Forcing a string to act as a number
view sourceprint?
var foo = 1;
var bar = ‘2’;

// coerce the string to a number
console.log(foo + Number(bar));

Example 2.10: Forcing a string to act as a number (using the unary-plus operator)
console.log(foo + +bar);

Advertisements

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