JavaScript Operators

Operators do work on values. For example + adds two numbers.


Arithmetic operators

OperatorMeaningExample
+Add5 + 2 is 7
-Subtract5 - 2 is 3
*Multiply5 * 2 is 10
/Divide5 / 2 is 2.5
%Remainder5 % 2 is 1
**Power2 ** 3 is 8
++, --Add or subtract 1x++
let a = 10, b = 3;
console.log(a + b);
console.log(a / b);
console.log(a % b);
console.log(a ** b);
let x = 5;
x++;
console.log(x);
Output of the above program is

13
3.3333333333333335
1
1000
6


Assignment operators

let n = 10;
n += 5;   // n = n + 5
n *= 2;   // n = n * 2
console.log(n);
Output of the above program is

30


Comparison operators

OperatorMeaning
===Equal value and type
!==Not equal
>, <Greater, less
>=, <=Greater or equal, less or equal
console.log(5 === 5);
console.log(5 !== "5");
console.log(7 > 3);
Output of the above program is

true
true
true


Logical operators

OperatorMeaning
&&AND: true only if both are true
||OR: true if at least one is true
!NOT: reverses true and false
let age = 25;
let hasId = true;
console.log(age >= 18 && hasId);
console.log(age < 18 || hasId);
console.log(!hasId);
Output of the above program is

true
true
false

|| and && return one of their values, which is often used to set a default.

let name = "" || "Guest";
console.log(name);
console.log(0 ?? 5);   // ?? only checks null and undefined
console.log(0 || 5);
Output of the above program is

Guest
0
5


Ternary operator

A short way to write if and else: condition ? valueIfTrue : valueIfFalse.

let marks = 60;
let result = marks >= 40 ? "Pass" : "Fail";
console.log(result);
Output of the above program is

Pass


Summary

  • Arithmetic: + - * / % **.
  • Compare with === and !==.
  • Combine conditions with &&, || and !.
  • Use ?? for defaults and ? : for short if/else.
  • Next: JavaScript Strings.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Write a JavaScript program to add two numbers
Write a JavaScript program to swap two variables
Interview Questions & Answers
What are the data types in JavaScript?
What is the difference between == and === in JavaScript?
What is NaN in JavaScript?
What is the difference between null and undefined?
What is scope in JavaScript?
What is the difference between var, let and const?
What is hoisting in JavaScript?