Operations on Numbers and Strings

Contact Us or call 1-877-932-8228
Operations on Numbers and Strings

Operations on Numbers and Strings

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

Addition vs. Concatenation

var foo = 1;
var bar = '2';

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

			// divide and multiply don't work for strings
console.log(foo / bar);  // so JavaScript coerces the string to a
			// number resulting in 0.5

Forcing a String to Act as a Number

var foo = 1;
var bar = '2';

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

The Number constructor, when called as a function (like above) will have the effect of casting its argument into a number. You could also use the unary plus operator, which does the same thing:

Forcing a String to Act as a Number (Using the Unary Plus Operator)

console.log(foo + +bar);
Next