Arithmetic operators
As you can probably guess, arithmetic operators are used to perform mathematical functions:
var add = 1 + 1; // 2 var subtract = 7 - 3; // 4 var multiply = 2.5 * 2; // 5 var divide = 4 / 2; // 2
These arithmetic operators can also be applied to variables with numeric values:
var my_num = 1 + 1; // 2 var new_num = my_num * 5; // 10 var my_arr = Array( 2, new_num ); // an array of numeric values var big_num = my_arr[0] * my_arr[1]; // 20
In addition to addition, the +
operator has another purpose: concatenation. Concatenation is the combining of two or more values into a new value. It is usually applied to strings:
var sentence = 'This is one phrase' + ' ' + 'and this is another' + '.';
but also applies to combining numbers and strings:
var new_str = 10 + '20'; // '1020'
Tip
When concatenating numbers with strings, the result is always a string.
There are also a few shorthand arithmetic operators you can use in specific cases, such as having a string or number add to itself:
var str = 'Hello there'; str += ', pilgrim.'; // 'Hello there, pilgrim.' var num = 2; num += 2; // 4
There is a shorthand for incrementing or decrementing a number by one:
var num = 2; num++; // 3 num--; // 2
Get Web Design in a Nutshell, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.