-
Notifications
You must be signed in to change notification settings - Fork 2
JS Arithmetic Operators
JavaScript provides the user with five arithmetic operators: +
, -
, *
, /
and %
. The operators are for addition, subtraction, multiplication, division and remainder respectively.
Syntax
a + b
Usage
2 + 3 // returns 5
true + 2 // interprets true as 1 and returns 3
false + 5 // interprets false as 0 and returns 5
true + "bar" // concatenates the boolean value and returns "truebar"
5 + "foo" // concatenates the string and the number and returns "5foo"
"foo" + "bar" // concatenates the strings and returns "foobar"
Hint: There is a handy increment operator that is a great shortcut when you're adding numbers by 1.
Syntax
a - b
Usage
2 - 3 // returns -1
3 - 2 // returns 1
false - 5 // interprets false as 0 and returns -5
true + 3 // interprets true as 1 and returns 4
5 + "foo" // returns NaN (Not a Number)
Hint: There is a handy decrement operator that is a great shortcut when you're subtracting numbers by 1.
Syntax
a * b
Usage
2 * 3 // returns 6
3 * -2 // returns -6
false * 5 // interprets false as 0 and returns 0
true * 3 // interprets true as 1 and returns 3
5 * "foo" // returns NaN (Not a Number)
Infinity * 0 // returns NaN
Infinity * Infinity // returns Infinity
Syntax
a / b
Usage
3 / 2 // returns 1.5
3.0 / 2/0 // returns 1.5
3 / 0 // returns Infinity
3.0 / 0.0 // returns Infinity
-3 / 0 // returns -Infinity
false / 5 // interprets false as 0 and returns 0
true / 2 // interprets true a 1 and returns 0.5
5 + "foo" // returns NaN (Not a Number)
Infinity / Infinity // returns NaN
Syntax
a % b
Usage
3 % 2 // returns 1
true % 5 // interprets true as 1 and returns 1
false % 4 // interprets false as 0 and returns 0
3 % "bar" // returns NaN
!Important! As you can see, you cannot perform any sort of operations on Infinity
.
Source: The amazing MDN.
Learn to code and help nonprofits. Join our open source community in 15 seconds at http://freecodecamp.com
Follow our Medium blog
Follow Quincy on Quora
Follow us on Twitter
Like us on Facebook
And be sure to click the "Star" button in the upper right of this page.
New to Free Code Camp?
JS Concepts
JS Language Reference
- arguments
- Array.prototype.filter
- Array.prototype.indexOf
- Array.prototype.map
- Array.prototype.pop
- Array.prototype.push
- Array.prototype.shift
- Array.prototype.slice
- Array.prototype.some
- Array.prototype.toString
- Boolean
- for loop
- for..in loop
- for..of loop
- String.prototype.split
- String.prototype.toLowerCase
- String.prototype.toUpperCase
- undefined
Other Links