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. JavaScript Basics
  2. Value Types
  3. true, false
  4. Operators
  5. Variable
  6. if then else
  7. for while do Loop
  8. Array Basics
  9. Object Basics
  10. RegExp Tutorial
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

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