JS: 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.

Or, use ** operator (in ES2016)

// 3 to the power of 2

console.log ( Math.pow(3,2) === 9 );

console.log ( 3 ** 2  === 9 );
// 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

let zz;

console.log ( ( zz = 3) + 1 );
// 4

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

let x = 3;

console.log (x += 2);            // 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」
let aa = 3;
let bb = ++ aa;

console.log(aa === 4); // true
console.log(bb === 4); // true

Logic Operators, Comparison Operators

See: JS: true, false

Bitwise Operators

JS: Bitwise Operators

JavaScript Basics

  1. How to Run JavaScript
  2. JS: How to Use Browser Console
  3. JavaScript Basics
  4. JS: Data Types
  5. JS: true, false
  6. JS: Operators
  7. JS: Variable
  8. JS: Branch Control: if then else, switch
  9. JS: for while do Loop
  10. JS: Array Basics
  11. JS: Object Basics
  12. JS: RegExp Tutorial
  13. JS: Throw Try Catch Finally
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon