In JavaScript, an operator is a special symbol that performs(you guessed it!) an operation on one or more operands. An operand is a value that is operated on by an operator. An expression is a combination of values, variables, and operators that produces a result.
Take a look at the example below where A and B are the operands and +, -, * and / are the operators.
Example 1: syntax
JavaScript has several arithmetic operators that perform basic math operations, such as addition, subtraction, multiplication, and division.
Example 2: Arithmetic operators
console.log(1 + 2); // 3 console.log(5 - 3); // 2 console.log(4 * 2); // 8 console.log(6 / 2); // 3
JavaScript has several assignment operators that assign a value to a variable. The most basic assignment operator is the equal sign (=), which assigns a value to a variable.
Example 3: Assignment operators
let x = 1; console.log(x) x = 2; console.log(x) x += 3; // x is now 5 console.log(x) x -= 1; // x is now 4 console.log(x) x *= 2; // x is now 8 console.log(x) x /= 4; // x is now 2 console.log(x)
JavaScript has several comparison operators that compare two values and return a boolean result. The most basic comparison operator is the equal sign (==), which checks if two values are equal.
Example 4: Comparison operators
console.log(1 == 2); // false console.log(1 == 1); // true console.log(1 === 2); // false console.log(1 === 1); // true console.log(1 > 2); // false console.log(1 < 2); // true console.log(1 >= 1); // true console.log(1 <= 1); // true
JavaScript has three logical operators that perform boolean operations: and (&&), or (||), and not (!).
Example 5: Logical operators
console.log(true && true); // true console.log(true && false); // false console.log(true || false); // true console.log(!true); // false
JavaScript has a ternary operator (?:) that performs a conditional operation. The ternary operator takes three operands: a condition, a value if the condition is true, and a value if the condition is false.
Example 6: Ternary operator
const x = 1; const y = x > 0 ? 'positive' : 'negative'; console.log(y); // 'positive'
Operators are a very fundamental concept in JavaScript. They are used in pretty much every application that has ever been written. We won’t be exploring any React-specific examples here as those would simply be too trivial.
1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Ternary Operator