JavaScript: Operators

By Xah Lee. Date: . Last updated: .

Arithmetic Operators

Basic arithmetic.

// basic arithmetic
3 + 4;      // 7
3 - 4;      // -1
3 * 4;      // 12
3 / 4;      // 0.75

// negation
-(3+4);     // -7

Integer Quotient, Remainder

// get integer quotient
Math.floor(7/2); // 3
// modular arithmetic; mod; get remainder
7 % 2; // 1

Power, Root

Use the Math.pow() method.

// 2 to the power of 3
Math.pow(2,3); // 8
// square root
Math.pow(9,1/2); // 3

// 3rd root
Math.pow(8,1/3); // 2

ECMAScript 2015 §Numbers and Dates#sec-math.pow

Assignment Operators

Assignment returns a value. It returns the value of the right-hand-side.

// assignment returns a value
var z = 5; // returns 5
console.log((z = 5)*2); // 10

ECMAScript 2015 §ECMAScript Language: Expressions#sec-assignment-operators

compound assignment operators
exampleequivalent to
x += yx = x + y
x -= yx = x - y
x *= yx = x * y
x /= yx = x / y
x %= yx = x % y
// assignment operator example

var x = 3;
var y = 2;

console.log(x += y);            // 5
console.log(x);                 // 5

Increment / Decrement Assignment

Increment / Decrement assignment operators
examplemeaning
++xequivalent to x=x+1 (returns new value)
--xequivalent to x=x-1 (returns new value)
x++similar to x=x+1 but returns old value
x--similar to x=x-1 but returns old value
// ++x is equivalent to x=x+1
var x = 3;
var aa = ++x;
console.log(aa); // 4

var y = 3;
var bb = (y = y + 1);
console.log(bb); // 4

Logic Operators, Comparison Operators

See: JavaScript: true, false

Bitwise Operators

JavaScript: Bitwise Operators

JavaScript Basics

  1. How to Run JavaScript
  2. JavaScript: How to Use Browser's JS Console
  3. JavaScript Tutorial by Example
  4. JavaScript: Data Types
  5. JavaScript: true, false
  6. JavaScript: Operators
  7. JavaScript: Variable
  8. JavaScript: Branch Control: if then else, switch
  9. JavaScript: for while do Loop
  10. JavaScript: Array Basics
  11. JavaScript: Object Basics
  12. JavaScript: RegExp Tutorial
  13. JavaScript: Throw Try Catch Finally
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.