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

Math.floor( x / y) → get integer quotient

console.log ( Math.floor(7/2) ); // 3

[see JS: Math]

Remainder

x % y → get remainder of x divided by y. (aka modular arithmetic)

both x and y can be decimal with fraction part.

console.log ( 7 % 2 ); // 1
console.log ( 7.4 % 2 ); // 1.4000000000000004
console.log ( 7 % 3.4 ); // 0.20000000000000018

Power

// 3 to the power of 2

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

console.log ( 3 ** 2  === 9 );

Root

Math.sqrt(x) → Square root.

Math.cbrt(x) → Cube root.

Math.pow(x, 1/n) → nth root.

x ** (1/n)n's root. (ES2016)

[see JS: Math]

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
compound assignment operators
examplesame as
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
++xsame as x=x+1 (returns new value)
--xsame as x=x-1 (returns new value)
x++like x=x+1 but returns old value
x--like x=x-1 but returns old value
// 「++ x」 is same as 「x = x + 1」
let aa = 3;
let bb = ++ aa;

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

Logic Operators, Comparison Operators

JS: true, false

Bitwise Operators

JS: Bitwise Operators

JavaScript Basics

  1. JavaScript Basics
  2. true, false
  3. Operators
  4. Branch Control
  5. Loop
  6. Array Basics
  7. Object Basics
  8. RegExp Basics
Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. CSS
  3. JavaScript
  4. JS Obj Ref
  5. DOM
  6. SVG
  7. Blog