In JavaScript, operators are symbols that are used to perform operations on values, such as arithmetic operations, logical operations, and comparison operations.
Here are some of the most commonly used operators in JavaScript:
Arithmetic Operators
Arithmetic operators are used to perform mathematical calculations on numeric values.
The basic arithmetic operators are:
As an example:
let x = 5;
let y = 2;
let z = x + y;
let w = x % y;
Comparison Operators
Comparison operators are used to compare two values and return a Boolean value (true or false).
The most common comparison operators are:
As an example:
let x = 5;
let y = 2;
console.log(x > y);
console.log(x == "5");
console.log(x === "5");
Logical Operators
Logical operators are used to combine Boolean values and return a Boolean result.
The most common logical operators are:
As an example:
let x = 5;
let y = 2;
let z = 3;
console.log(x > y && z > y);
console.log(x < y || z < y);
console.log(!(x > y));
Assignment Operators
Assignment operators are used to assign values to variables.
The basic assignment operator is the equals sign (=)
, but there are also shorthand assignment operators that combine an arithmetic operator with the equals sign.
The most common arithmetic operators are:
As an example:
let x = 5;
x += 3;
console.log(x);
Increment and Decrement Operators
Increment and decrement operators are used to increase or decrease the value of a variable by 1.
As an example:
let x = 5;
x++;
console.log(x);
Conditional Operator (ternary operator)
The conditional operator (also called the ternary operator) is a shorthand way of writing an if-else
statement.
condition ? expression1 : expression2;
As an example:
let x = 5;
let y = x > 3 ? "greater than 3" : "less than or equal to 3";
console.log(y);
Bitwise Operators
Bitwise operators perform operations on the binary representation of numeric values.
As an example:
let x = 5;
let y = 3;
console.log(x & y);
console.log(x | y);
console.log(~x);
Understanding how to use operators is crucial to writing JavaScript code that performs the necessary operations on data.