JavaScript Operators
JavaScript operators are used to perform operations on variables and values. Here are some examples you can go over to get a quick grasp of them.
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations. this should be pretty obvious.
let a = 10;
let b = 3;
// Addition
console.log(a + b); // Output: 13
// Subtraction
console.log(a - b); // Output: 7
// Multiplication
console.log(a * b); // Output: 30
// Division
console.log(a / b); // Output: 3.3333333333333335
// Modulus (remainder)
console.log(a % b); // Output: 1
// Increment
let c = 5;
c++;
console.log(c); // Output: 6
// Decrement
c--;
console.log(c); // Output: 5
Assignment Operators
Assignment operators are used to assign values to variables.
let x = 10; // Assignment
// Add and assign
x += 5; // Equivalent to x = x + 5
console.log(x); // Output: 15
// Subtract and assign
x -= 3; // Equivalent to x = x - 3
console.log(x); // Output: 12
// Multiply and assign
x *= 2; // Equivalent to x = x * 2
console.log(x); // Output: 24
// Divide and assign
x /= 4; // Equivalent to x = x / 4
console.log(x); // Output: 6
// Modulus and assign
x %= 4; // Equivalent to x = x % 4
console.log(x); // Output: 2
Comparison Operators
Comparison operators are used to compare two values and return a boolean (true
or false
).
let num1 = 10;
let num2 = 20;
// Equal to
console.log(num1 == num2); // Output: false
// Strict equal to (checks both value and type)
console.log(num1 === 10); // Output: true
console.log(num1 === '10'); // Output: false
// Not equal to
console.log(num1 != num2); // Output: true
// Strict not equal to
console.log(num1 !== '10'); // Output: true
// Greater than
console.log(num1 > num2); // Output: false
// Less than
console.log(num1 < num2); // Output: true
// Greater than or equal to
console.log(num1 >= 10); // Output: true
// Less than or equal to
console.log(num1 <= 20); // Output: true
Logical Operators
Logical operators are used to combine multiple conditions.
let isTrue = true;
let isFalse = false;
// Logical AND
console.log(isTrue && isFalse); // Output: false
console.log(isTrue && true); // Output: true
// Logical OR
console.log(isTrue || isFalse); // Output: true
console.log(false || isFalse); // Output: false
// Logical NOT
console.log(!isTrue); // Output: false
console.log(!isFalse); // Output: true
Ternary Operator
The ternary operator is a shorthand way of performing conditional checks. It has the syntax:
condition ? expression1 : expression2
let age = 18;
let canVote = age >= 18 ? 'Eligible to vote' : 'Not eligible to vote';
console.log(canVote); // Output: Eligible to vote
let score = 50;
let result = score > 40 ? 'Pass' : 'Fail';
console.log(result); // Output: Pass
Last updated on