JavaScript Operators
Operators do work on values. For example + adds two numbers.
Arithmetic operators
| Operator | Meaning | Example |
|---|---|---|
+ | Add | 5 + 2 is 7 |
- | Subtract | 5 - 2 is 3 |
* | Multiply | 5 * 2 is 10 |
/ | Divide | 5 / 2 is 2.5 |
% | Remainder | 5 % 2 is 1 |
** | Power | 2 ** 3 is 8 |
++, -- | Add or subtract 1 | x++ |
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
| Operator | Meaning |
|---|---|
=== | 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
| Operator | Meaning |
|---|---|
&& | 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 |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |