February 2006
Intermediate to advanced
826 pages
63h 42m
English
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; // 2These 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]; // 20In 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'
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; // 4There is a shorthand for incrementing or decrementing a number by one:
var num = 2;
num++; // 3
num--; // 2Read now
Unlock full access