Skip to main content

JavaScript Operators

Operators are symbols that are used to perform operations on operands. In JavaScript, operators allow you to manipulate values, compare them, combine them, and perform various computations. Understanding operators is crucial for writing efficient JavaScript code.

Introduction to Operators

Operators in JavaScript can be categorized into several types:

  1. Arithmetic Operators
  2. Assignment Operators
  3. Comparison Operators
  4. Logical Operators
  5. String Operators
  6. Unary Operators
  7. Bitwise Operators
  8. Ternary (Conditional) Operator

Let's explore each type in detail.

Arithmetic Operators

Arithmetic operators perform mathematical operations on numeric values.

OperatorDescriptionExample
+Addition5 + 2 = 7
-Subtraction5 - 2 = 3
*Multiplication5 * 2 = 10
/Division5 / 2 = 2.5
%Modulus (Remainder)5 % 2 = 1
**Exponentiation5 ** 2 = 25
++Incrementlet a = 5; a++; // a = 6
--Decrementlet a = 5; a--; // a = 4

Example: Basic Arithmetic

javascript
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

// Exponentiation
console.log(a ** b); // Output: 1000

Pre-increment and Post-increment

javascript
let x = 5;
let y = x++; // Post-increment: y gets the current value of x (5), then x is incremented to 6
console.log(x, y); // Output: 6, 5

let p = 5;
let q = ++p; // Pre-increment: p is incremented to 6 first, then q gets the new value of p (6)
console.log(p, q); // Output: 6, 6

Assignment Operators

Assignment operators assign values to JavaScript variables.

OperatorExampleSame As
=x = yx = y
+=x += yx = x + y
-=x -= yx = x - y
*=x *= yx = x * y
/=x /= yx = x / y
%=x %= yx = x % y
**=x **= yx = x ** y

Example: Assignment Operators

javascript
let x = 10;

// Add and assign
x += 5; // x = x + 5
console.log(x); // Output: 15

// Subtract and assign
x -= 3; // x = x - 3
console.log(x); // Output: 12

// Multiply and assign
x *= 2; // x = x * 2
console.log(x); // Output: 24

// Divide and assign
x /= 4; // x = x / 4
console.log(x); // Output: 6

Comparison Operators

Comparison operators are used to compare values and return a boolean result (true or false).

OperatorDescriptionExample
==Equal to (value)5 == "5" returns true
===Equal to (value and type)5 === "5" returns false
!=Not equal to (value)5 != "6" returns true
!==Not equal to (value and type)5 !== "5" returns true
>Greater than5 > 3 returns true
<Less than5 < 3 returns false
>=Greater than or equal to5 >= 5 returns true
<=Less than or equal to5 <= 4 returns false

Example: Comparison Operators

javascript
// Equal to (==) - Compares values, not types
console.log(5 == 5); // Output: true
console.log(5 == "5"); // Output: true

// Strict equal to (===) - Compares both values and types
console.log(5 === 5); // Output: true
console.log(5 === "5"); // Output: false

// Not equal to (!=)
console.log(5 != 8); // Output: true
console.log(5 != "5"); // Output: false (values are equal)

// Strict not equal to (!==)
console.log(5 !== 8); // Output: true
console.log(5 !== "5"); // Output: true (types are different)

// Greater than (>)
console.log(10 > 5); // Output: true

// Less than (<)
console.log(10 < 5); // Output: false

// Greater than or equal to (>=)
console.log(10 >= 10); // Output: true

// Less than or equal to (<=)
console.log(10 <= 5); // Output: false

Logical Operators

Logical operators are used to determine the logic between variables or values.

OperatorDescriptionExample
&&AND - Returns true if both statements are true(x > 5 && y < 10)
||OR - Returns true if one of the statements is true(x > 5 || y < 10)
!NOT - Reverses the result, returns false if the result is true!(x > 5)

Example: Logical Operators

javascript
let x = 10;
let y = 5;

// AND operator (&&)
console.log(x > 5 && y < 10); // Output: true (both conditions are true)
console.log(x < 5 && y < 10); // Output: false (first condition is false)

// OR operator (||)
console.log(x > 5 || y > 10); // Output: true (first condition is true)
console.log(x < 5 || y > 10); // Output: false (both conditions are false)

// NOT operator (!)
console.log(!(x > 5)); // Output: false (x > 5 is true, so NOT true is false)
console.log(!(y > 10)); // Output: true (y > 10 is false, so NOT false is true)

Short-circuit Evaluation

Logical operators evaluate from left to right and "short-circuit" as soon as the result is determined:

javascript
// With AND (&&), if the first operand is falsy, the second is not evaluated
let a = 0;
let b = "not executed";
let result = a && b;
console.log(result); // Output: 0 (a is falsy, so result is a)

// With OR (||), if the first operand is truthy, the second is not evaluated
let c = "truthy value";
let d = "not executed";
let anotherResult = c || d;
console.log(anotherResult); // Output: "truthy value" (c is truthy, so result is c)

String Operators

The + operator can be used to concatenate (join) strings.

Example: String Concatenation

javascript
let firstName = "John";
let lastName = "Doe";

// Using the + operator for concatenation
let fullName = firstName + " " + lastName;
console.log(fullName); // Output: "John Doe"

// Using += for concatenation
let greeting = "Hello, ";
greeting += fullName;
console.log(greeting); // Output: "Hello, John Doe"

Unary Operators

Unary operators work with only one operand.

Example: Unary Operators

javascript
// Unary plus (+) - converts to number
let a = "5";
console.log(+a); // Output: 5 (number)
console.log(typeof +a); // Output: "number"

// Unary minus (-) - converts to number and negates
console.log(-a); // Output: -5
console.log(typeof -a); // Output: "number"

// Typeof - returns the type of a variable
console.log(typeof 42); // Output: "number"
console.log(typeof "hello"); // Output: "string"

// Delete - removes a property from an object
let person = { name: "John", age: 30 };
delete person.age;
console.log(person); // Output: { name: "John" }

Bitwise Operators

Bitwise operators work on 32-bit numbers at the bit level. Although less common in everyday JavaScript, they're important to know.

OperatorDescriptionExample
&AND5 & 1 = 1
|OR5 | 1 = 5
^XOR5 ^ 1 = 4
~NOT~5 = -6
<<Left shift5 << 1 = 10
>>Right shift5 >> 1 = 2
>>>Unsigned right shift5 >>> 1 = 2

Example: Bitwise Operators

javascript
// Bitwise AND (&)
console.log(5 & 1); // Output: 1
// 5 in binary is 101, 1 in binary is 001
// 101 & 001 = 001 (which is 1 in decimal)

// Bitwise OR (|)
console.log(5 | 1); // Output: 5
// 5 in binary is 101, 1 in binary is 001
// 101 | 001 = 101 (which is 5 in decimal)

// Left shift (<<)
console.log(5 << 1); // Output: 10
// 5 in binary is 101
// 101 << 1 = 1010 (which is 10 in decimal)

Ternary (Conditional) Operator

The ternary operator is a shorthand for the if-else statement.

Syntax: condition ? expressionIfTrue : expressionIfFalse

Example: Ternary Operator

javascript
let age = 19;
let status = age >= 18 ? "Adult" : "Minor";
console.log(status); // Output: "Adult"

// Nested ternary operator
let score = 75;
let grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "D";
console.log(grade); // Output: "C"

Operator Precedence

Operator precedence determines the order in which operators are evaluated. Operators with higher precedence are evaluated first.

javascript
// Multiplication (*) has higher precedence than addition (+)
let result = 5 + 10 * 2;
console.log(result); // Output: 25 (not 30)

// Parentheses can be used to change the precedence
let anotherResult = (5 + 10) * 2;
console.log(anotherResult); // Output: 30

Real-world Applications

Example 1: Calculating Discounts

javascript
function calculateDiscount(price, discountPercentage) {
// Calculate the discount amount and final price
const discountAmount = price * (discountPercentage / 100);
const finalPrice = price - discountAmount;

return {
originalPrice: price,
discountPercentage,
discountAmount,
finalPrice
};
}

const productPrice = 99.99;
const discountPercentage = 15;
const result = calculateDiscount(productPrice, discountPercentage);

console.log(`Original price: $${result.originalPrice.toFixed(2)}`);
console.log(`Discount: ${result.discountPercentage}% ($${result.discountAmount.toFixed(2)})`);
console.log(`Final price: $${result.finalPrice.toFixed(2)}`);

Output:

Original price: $99.99
Discount: 15% ($15.00)
Final price: $84.99

Example 2: Form Validation

javascript
function validateForm(username, password, email) {
// Check for empty fields with OR operator
if (username === "" || password === "" || email === "") {
return "All fields are required";
}

// Check for valid username length with AND operator
if (username.length >= 3 && username.length <= 20) {
// Username is valid
} else {
return "Username must be between 3 and 20 characters";
}

// Check for password strength
const hasUppercase = /[A-Z]/.test(password);
const hasNumber = /[0-9]/.test(password);
const hasSpecialChar = /[!@#$%^&*]/.test(password);

// Use logical AND to check all conditions
if (password.length >= 8 && hasUppercase && hasNumber && hasSpecialChar) {
// Password is strong
} else {
return "Password must be at least 8 characters with uppercase, number, and special character";
}

// Check email format using ternary operator
const isEmailValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)
? true
: false;

return isEmailValid ? "Form validation successful" : "Invalid email format";
}

// Usage
console.log(validateForm("john_doe", "Passw0rd!", "[email protected]")); // Output: "Form validation successful"
console.log(validateForm("jo", "Passw0rd!", "[email protected]")); // Output: "Username must be between 3 and 20 characters"
console.log(validateForm("john_doe", "password", "[email protected]")); // Output: "Password must be at least 8 characters with uppercase, number, and special character"

Summary

In this tutorial, we've explored the various operators in JavaScript:

  • Arithmetic operators (+, -, *, /, %, **) perform mathematical calculations
  • Assignment operators (=, +=, -=, etc.) assign values to variables
  • Comparison operators (==, ===, !=, !==, >, <, etc.) compare values
  • Logical operators (&&, ||, !) combine boolean expressions
  • String operators (+, +=) concatenate strings
  • Unary operators (+, -, typeof, delete) work with a single operand
  • Bitwise operators (&, |, ^, ~, <<, >>, >>>) manipulate bits
  • Ternary operator (? :) provides a shorthand for if-else statements

Understanding operators is fundamental to writing effective JavaScript code. They allow you to manipulate data, control program flow, and implement complex logic in your applications.

Exercises

  1. Write a function that calculates the area and perimeter of a rectangle using arithmetic operators.
  2. Create a function that checks if a number is even or odd using the modulus operator and returns a string.
  3. Write a program that determines if a user is eligible to vote based on their age and citizenship status using logical operators.
  4. Create a simple calculator that can perform addition, subtraction, multiplication, and division based on user input.
  5. Write a program that converts temperatures between Celsius and Fahrenheit using operators.

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)