Operators In JavaScript

javascript dev.to

JavaScript Operators

Operators in JavaScript are symbols or keywords used to perform operations on values and variables. They are fundamental to writing expressions, performing calculations, comparing values, assigning data, and controlling program logic. Some operators are used frequently in everyday JavaScript development, while others are more specialized. The important operators to understand are arithmetic, assignment, comparison, logical, increment and decrement, ternary, typeof, nullish coalescing, and optional chaining.

Arithmetic Operators

Arithmetic operators are used to perform mathematical operations. The commonly used operators are +, -, *, /, %, and **. The + operator performs addition, - performs subtraction, * performs multiplication, / performs division, % returns the remainder of a division, and ** performs exponentiation.

let a = 10;
let b = 3;

console.log(a + b);  // 13
console.log(a - b);  // 7
console.log(a * b);  // 30
console.log(a / b);  // 3.333...
console.log(a % b);  // 1
console.log(a ** b); // 1000
Enter fullscreen mode Exit fullscreen mode

The remainder operator % is particularly useful in conditions. For example, number % 2 === 0 can be used to determine whether a number is even.

Assignment Operators

Assignment operators are used to assign values to variables. The basic assignment operator is =. JavaScript also provides compound assignment operators such as +=, -=, *=, /=, and %=. These operators perform an operation and assign the resulting value back to the same variable.

let score = 50;

score += 10; // 60
score -= 5;  // 55
score *= 2;  // 110
score /= 2;  // 55
Enter fullscreen mode Exit fullscreen mode

For example, score += 10 is equivalent to score = score + 10. Compound assignment operators are useful when repeatedly modifying the value of a variable.

Comparison Operators

Comparison operators compare two values and return a Boolean result, either true or false. Common comparison operators include >, <, >=, <=, ===, and !==. They are frequently used in conditional statements and loops.

let age = 20;

console.log(age > 18);  // true
console.log(age < 18);  // false
console.log(age >= 20); // true
console.log(age <= 20); // true
Enter fullscreen mode Exit fullscreen mode

An important distinction in JavaScript is between == and ===. The == operator performs loose equality and can convert the types of the operands before comparison, whereas === performs strict equality and checks both the value and type.

console.log(5 == "5");  // true
console.log(5 === "5"); // false
Enter fullscreen mode Exit fullscreen mode

Because strict equality avoids unexpected type conversions, === and !== are generally preferred in modern JavaScript.

Logical Operators

Logical operators are used to combine or modify conditions. The three primary logical operators are &&, ||, and !. The && operator returns true when both conditions are true, || returns true when at least one condition is true, and ! reverses a Boolean value.

let age = 25;

console.log(age >= 18 && age <= 60); // true
console.log(age === 18 || age === 25); // true

let isLoggedIn = true;
console.log(!isLoggedIn); // false
Enter fullscreen mode Exit fullscreen mode

These operators are commonly used when multiple conditions need to be evaluated together.

Increment and Decrement Operators

The increment operator ++ increases a value by one, while the decrement operator -- decreases a value by one. They are commonly used in loops and counters.

let count = 5;

count++;
console.log(count); // 6

count--;
console.log(count); // 5
Enter fullscreen mode Exit fullscreen mode

There is an important difference between prefix and postfix forms. x++ returns the current value before incrementing it, while ++x increments the value before returning it.

let x = 5;

console.log(x++); // 5
console.log(x);   // 6

let y = 5;

console.log(++y); // 6
Enter fullscreen mode Exit fullscreen mode

Ternary Operator

The ternary operator ?: provides a concise way to evaluate a condition and select one of two values. Its syntax is condition ? valueIfTrue : valueIfFalse.

let age = 20;

let result = age >= 18 ? "Adult" : "Minor";

console.log(result); // Adult
Enter fullscreen mode Exit fullscreen mode

The ternary operator is useful for simple conditional expressions. For complex logic, a traditional if...else statement is generally more readable.

typeof Operator

The typeof operator is used to determine the type of a value. It returns a string representing the type.

console.log(typeof "Hello");   // "string"
console.log(typeof 100);       // "number"
console.log(typeof true);      // "boolean"
console.log(typeof undefined); // "undefined"
Enter fullscreen mode Exit fullscreen mode

One well-known JavaScript behavior is that typeof null returns "object". This is a historical language quirk and does not mean that null is actually an object.

Nullish Coalescing Operator

The nullish coalescing operator ?? is used to provide a fallback value when the expression on the left is null or undefined.

let username;

let name = username ?? "Guest";

console.log(name); // Guest
Enter fullscreen mode Exit fullscreen mode

It is important to distinguish ?? from ||. The || operator considers all falsy values, including 0, false, and an empty string, whereas ?? only considers null and undefined.

let number = 0;

console.log(number || 10); // 10
console.log(number ?? 10); // 0
Enter fullscreen mode Exit fullscreen mode

Optional Chaining Operator

The optional chaining operator ?. allows properties or methods to be accessed without throwing an error when an intermediate value is null or undefined. It is particularly useful when working with nested objects or data received from APIs.

let user = {
    name: "Abimanyu"
};

console.log(user.address?.city); // undefined
Enter fullscreen mode Exit fullscreen mode

Normally, user.address.city would throw an error because address is undefined. With user.address?.city, JavaScript checks whether address is available before attempting to access city. Optional chaining can also be used at multiple levels, such as user?.address?.city, to safely access nested properties.

Source: dev.to

arrow_back Back to Tutorials