Progress3 of 20 topics

15% complete

JavaScript Operators

Operators are special symbols that perform operations on values and variables. They're like the verbs in a sentence - they tell JavaScript to do something with your data. In this tutorial, we'll explore all the essential operators in JavaScript.

Why Operators Matter

Operators let you:

  • Perform mathematical calculations
  • Compare values to make decisions
  • Combine conditions with logical operators
  • Assign values to variables efficiently
  • Manipulate strings and other data types

Arithmetic Operators

Arithmetic operators perform mathematical operations on numbers.

OperatorNameExampleResult
+Addition5 + 27
-Subtraction5 - 23
*Multiplication5 * 210
/Division5 / 22.5
%Modulus (Remainder)5 % 21
**Exponentiation5 ** 225
++Incrementlet x = 5; x++;x becomes 6
--Decrementlet x = 5; x--;x becomes 4
JavaScript
1// Basic arithmetic
2let a = 10;
3let b = 3;
4
5let sum = a + b; // 13
6let difference = a - b; // 7
7let product = a * b; // 30
8let quotient = a / b; // 3.3333...
9let remainder = a % b; // 1
10let power = a ** b; // 1000 (10 to the power of 3)
11
12// Increment and decrement
13let count = 0;
14count++; // count is now 1
15count--; // count is back to 0
16
17// Pre vs Post increment
18let x = 5;
19let y = x++; // y = 5, x = 6
20let z = ++x; // x = 7, z = 7
21
22// With strings
23let greeting = "Hello " + "World"; // "Hello World"

Modulus Operator: Practical Uses

The modulus (%) operator returns the remainder after division and has several useful applications:

  • Check if a number is even or odd: x % 2 === 0 means x is even
  • Cycle through a range (like creating a circular list): index = (index + 1) % array.length
  • Format time (converting seconds to minutes:seconds): minutes = Math.floor(seconds / 60); remainingSeconds = seconds % 60;

Assignment Operators

Assignment operators assign values to variables, often combining the assignment with another operation.

OperatorExampleEquivalent to
=x = 5x = 5
+=x += 5x = x + 5
-=x -= 5x = x - 5
*=x *= 5x = x * 5
/=x /= 5x = x / 5
%=x %= 5x = x % 5
**=x **= 2x = x ** 2
JavaScript
1// Assignment operators
2let score = 10;
3
4score += 5; // score is now 15 (10 + 5)
5score -= 3; // score is now 12 (15 - 3)
6score *= 2; // score is now 24 (12 * 2)
7score /= 4; // score is now 6 (24 / 4)
8score %= 4; // score is now 2 (6 % 4)
9score **= 3; // score is now 8 (2 ** 3)
10
11// With strings
12let greeting = "Hello";
13greeting += " World"; // greeting is now "Hello World"

Comparison Operators

Comparison operators compare values and return a boolean result (true or false). They're essential for conditional logic.

OperatorNameExampleResult
==Equal (value)5 == "5"true
===Strict equal (value and type)5 === "5"false
!=Not equal (value)5 != "5"false
!==Strict not equal (value and type)5 !== "5"true
>Greater than5 > 3true
<Less than5 < 3false
>=Greater than or equal5 >= 5true
<=Less than or equal5 <= 3false
JavaScript
1// Comparison operators
2let a = 5;
3let b = "5";
4let c = 10;
5
6// Equality
7console.log(a == b); // true (values are equal, ignores type)
8console.log(a === b); // false (different types)
9console.log(a != c); // true (values are not equal)
10console.log(a !== b); // true (different types)
11
12// Relational
13console.log(a > 3); // true (5 is greater than 3)
14console.log(a < c); // true (5 is less than 10)
15console.log(a >= 5); // true (5 is greater than or equal to 5)
16console.log(a <= 4); // false (5 is not less than or equal to 4)
17
18// Common use case: conditionals
19if (a === 5) {
20 console.log("a is exactly 5");
21}
22
23if (c > a) {
24 console.log("c is greater than a");
25}

== vs. ===

Always prefer === (strict equality) over == (loose equality). The strict equality operator checks both value and type, which helps avoid unexpected bugs.

JavaScript
console.log(0 == false); // true (unexpected)
console.log(0 === false); // false (correct)
console.log("5" == 5); // true (unexpected)
console.log("5" === 5); // false (correct)
console.log("" == 0); // true (unexpected)
console.log("" === 0); // false (correct)

Logical Operators

Logical operators perform logical operations and are typically used with boolean values.

OperatorNameExampleResult
&&Logical ANDtrue && truetrue
||Logical ORtrue || falsetrue
!Logical NOT!truefalse
JavaScript
1// Logical operators
2let isLoggedIn = true;
3let hasPermission = false;
4
5// Logical AND: both must be true
6if (isLoggedIn && hasPermission) {
7 console.log("You can access the admin panel");
8} else {
9 console.log("Access denied"); // This will run
10}
11
12// Logical OR: at least one must be true
13if (isLoggedIn || hasPermission) {
14 console.log("You have some level of access"); // This will run
15}
16
17// Logical NOT: inverts the value
18if (!hasPermission) {
19 console.log("You don't have permission"); // This will run
20}
21
22// Combining logical operators
23let isAdmin = true;
24let isOwner = false;
25
26if ((isAdmin || isOwner) && isLoggedIn) {
27 console.log("Welcome to the control panel"); // This will run
28}

Short-circuit Evaluation

Logical operators in JavaScript use "short-circuit" evaluation, which can be used to write concise code.

JavaScript
1// Short-circuit with &&
2// If the first value is false, the second won't be evaluated
3let result1 = false && someFunction(); // someFunction is never called
4
5// Short-circuit with ||
6// If the first value is true, the second won't be evaluated
7let result2 = true || someFunction(); // someFunction is never called
8
9// Practical examples:
10
11// Set default values
12let username = userInput || "Guest"; // If userInput is empty/falsy, use "Guest"
13
14// Call a function only if a condition is met
15isLoggedIn && showDashboard(); // Only call showDashboard if isLoggedIn is true
16
17// Checking for null before accessing properties
18let user = null;
19let userName = user && user.name; // Prevents "Cannot read property 'name' of null"

String Operators

Strings have their own special operators in JavaScript.

JavaScript
1// String concatenation with +
2let firstName = "John";
3let lastName = "Doe";
4let fullName = firstName + " " + lastName; // "John Doe"
5
6// String concatenation with +=
7let greeting = "Hello";
8greeting += " World"; // "Hello World"
9
10// Template literals (modern way)
11let age = 30;
12let message = `${firstName} is ${age} years old`; // "John is 30 years old"
13
14// Comparing strings
15console.log("apple" < "banana"); // true (alphabetically, "a" comes before "b")
16console.log("apple" === "Apple"); // false (case-sensitive comparison)
17console.log("apple".toLowerCase() === "Apple".toLowerCase()); // true (case-insensitive)

Conditional (Ternary) Operator

The conditional operator is a shorthand for an if-else statement.

JavaScript
1// Syntax: condition ? valueIfTrue : valueIfFalse
2
3// Instead of:
4let message;
5if (age >= 18) {
6 message = "You can vote";
7} else {
8 message = "Too young to vote";
9}
10
11// You can write:
12let age = 20;
13let message = age >= 18 ? "You can vote" : "Too young to vote";
14
15// Nested ternary operators (use carefully, can reduce readability)
16let greeting = hour < 12 ? "Good morning" : hour < 18 ? "Good afternoon" : "Good evening";
17
18// Ternary with functions
19let canAccess = userRole === "admin" ? getAdminContent() : getRegularContent();

Type Operators

JavaScript includes operators to check types and structures.

JavaScript
1// typeof operator
2console.log(typeof "hello"); // "string"
3console.log(typeof 42); // "number"
4console.log(typeof true); // "boolean"
5console.log(typeof undefined); // "undefined"
6console.log(typeof null); // "object" (this is a known JavaScript bug)
7console.log(typeof {}); // "object"
8console.log(typeof []); // "object" (arrays are objects in JavaScript)
9console.log(typeof function(){}); // "function"
10
11// instanceof operator (checks if an object is an instance of a class)
12let arr = [1, 2, 3];
13console.log(arr instanceof Array); // true
14
15let date = new Date();
16console.log(date instanceof Date); // true
17
18// Better way to check for arrays
19console.log(Array.isArray(arr)); // true
20console.log(Array.isArray({})); // false

Bitwise Operators

Bitwise operators perform operations on binary representations of numbers. These are advanced operators that you might not use frequently as a beginner.

JavaScript
1// Bitwise operators (work on binary representation of numbers)
2let a = 5; // binary: 101
3let b = 3; // binary: 011
4
5console.log(a & b); // Bitwise AND: 1 (binary: 001)
6console.log(a | b); // Bitwise OR: 7 (binary: 111)
7console.log(a ^ b); // Bitwise XOR: 6 (binary: 110)
8console.log(~a); // Bitwise NOT: -6
9console.log(a << 1); // Left shift: 10 (binary: 1010)
10console.log(a >> 1); // Right shift: 2 (binary: 10)

Operator Precedence

Operator precedence determines the order in which operators are evaluated. It's similar to the order of operations in mathematics (PEMDAS).

JavaScript
1// Operator precedence examples
2let result = 2 + 3 * 4; // 14, not 20 (multiplication happens first)
3let result2 = (2 + 3) * 4; // 20 (parentheses override default precedence)
4
5// Multiple operators
6let x = 5;
7let y = 10;
8let z = 15;
9
10let result3 = x + y * z; // 155
11let result4 = x + y > z && z > y; // false (comparison happens before logical AND)
12
13// When in doubt, use parentheses for clarity
14let result5 = (x + y) > z && (z > y); // false, but clearer intention

Practice Exercises

Try these exercises to reinforce your understanding of JavaScript operators:

JavaScript
// 1. Calculate and display:
// - The area of a rectangle with width 7 and height 5
// - The perimeter of the same rectangle
// 2. Calculate the average of three test scores: 85, 90, and 78
// 3. Determine if a person can vote:
// - Create a variable for age
// - Create a boolean variable that indicates if they can vote (18 or older)
// 4. Create a temperature converter:
// - Convert 77°F to Celsius (formula: (F - 32) * 5/9)
// - Convert 25°C to Fahrenheit (formula: C * 9/5 + 32)
// 5. Create a shopping cart total:
// - Add 3 items with prices: $10.99, $4.50, and $2.75
// - Apply a 10% discount if the total is over $15
// - Calculate and display the final total

Summary

In this tutorial, you've learned about:

  • Arithmetic operators for mathematical calculations
  • Assignment operators for efficient variable value updates
  • Comparison operators for comparing values
  • Logical operators for combining conditions
  • String operators for working with text
  • The conditional (ternary) operator for concise conditionals
  • Type operators for checking data types
  • Operator precedence rules

Understanding operators is crucial for writing effective JavaScript code. In the next tutorial, you'll learn about control flow structures like conditional statements and loops, which work hand-in-hand with the operators you've learned here.

Related Tutorials

Learn about different types of data and how to store them in JavaScript.

Learn more

Learn about conditional statements and loops in JavaScript.

Learn more

Learn how to create and use functions in JavaScript.

Learn more