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.
Operator | Name | Example | Result |
---|---|---|---|
+ | Addition | 5 + 2 | 7 |
- | Subtraction | 5 - 2 | 3 |
* | Multiplication | 5 * 2 | 10 |
/ | Division | 5 / 2 | 2.5 |
% | Modulus (Remainder) | 5 % 2 | 1 |
** | Exponentiation | 5 ** 2 | 25 |
++ | Increment | let x = 5; x++; | x becomes 6 |
-- | Decrement | let x = 5; x--; | x becomes 4 |
1// Basic arithmetic2let a = 10;3let b = 3;45let sum = a + b; // 136let difference = a - b; // 77let product = a * b; // 308let quotient = a / b; // 3.3333...9let remainder = a % b; // 110let power = a ** b; // 1000 (10 to the power of 3)1112// Increment and decrement13let count = 0;14count++; // count is now 115count--; // count is back to 01617// Pre vs Post increment18let x = 5;19let y = x++; // y = 5, x = 620let z = ++x; // x = 7, z = 72122// With strings23let 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.
Operator | Example | Equivalent to |
---|---|---|
= | x = 5 | x = 5 |
+= | x += 5 | x = x + 5 |
-= | x -= 5 | x = x - 5 |
*= | x *= 5 | x = x * 5 |
/= | x /= 5 | x = x / 5 |
%= | x %= 5 | x = x % 5 |
**= | x **= 2 | x = x ** 2 |
1// Assignment operators2let score = 10;34score += 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)1011// With strings12let 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.
Operator | Name | Example | Result |
---|---|---|---|
== | 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 than | 5 > 3 | true |
< | Less than | 5 < 3 | false |
>= | Greater than or equal | 5 >= 5 | true |
<= | Less than or equal | 5 <= 3 | false |
1// Comparison operators2let a = 5;3let b = "5";4let c = 10;56// Equality7console.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)1112// Relational13console.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)1718// Common use case: conditionals19if (a === 5) {20 console.log("a is exactly 5");21}2223if (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.
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.
Operator | Name | Example | Result |
---|---|---|---|
&& | Logical AND | true && true | true |
|| | Logical OR | true || false | true |
! | Logical NOT | !true | false |
1// Logical operators2let isLoggedIn = true;3let hasPermission = false;45// Logical AND: both must be true6if (isLoggedIn && hasPermission) {7 console.log("You can access the admin panel");8} else {9 console.log("Access denied"); // This will run10}1112// Logical OR: at least one must be true13if (isLoggedIn || hasPermission) {14 console.log("You have some level of access"); // This will run15}1617// Logical NOT: inverts the value18if (!hasPermission) {19 console.log("You don't have permission"); // This will run20}2122// Combining logical operators23let isAdmin = true;24let isOwner = false;2526if ((isAdmin || isOwner) && isLoggedIn) {27 console.log("Welcome to the control panel"); // This will run28}
Short-circuit Evaluation
Logical operators in JavaScript use "short-circuit" evaluation, which can be used to write concise code.
1// Short-circuit with &&2// If the first value is false, the second won't be evaluated3let result1 = false && someFunction(); // someFunction is never called45// Short-circuit with ||6// If the first value is true, the second won't be evaluated7let result2 = true || someFunction(); // someFunction is never called89// Practical examples:1011// Set default values12let username = userInput || "Guest"; // If userInput is empty/falsy, use "Guest"1314// Call a function only if a condition is met15isLoggedIn && showDashboard(); // Only call showDashboard if isLoggedIn is true1617// Checking for null before accessing properties18let user = null;19let userName = user && user.name; // Prevents "Cannot read property 'name' of null"
String Operators
Strings have their own special operators in JavaScript.
1// String concatenation with +2let firstName = "John";3let lastName = "Doe";4let fullName = firstName + " " + lastName; // "John Doe"56// String concatenation with +=7let greeting = "Hello";8greeting += " World"; // "Hello World"910// Template literals (modern way)11let age = 30;12let message = `${firstName} is ${age} years old`; // "John is 30 years old"1314// Comparing strings15console.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.
1// Syntax: condition ? valueIfTrue : valueIfFalse23// Instead of:4let message;5if (age >= 18) {6 message = "You can vote";7} else {8 message = "Too young to vote";9}1011// You can write:12let age = 20;13let message = age >= 18 ? "You can vote" : "Too young to vote";1415// Nested ternary operators (use carefully, can reduce readability)16let greeting = hour < 12 ? "Good morning" : hour < 18 ? "Good afternoon" : "Good evening";1718// Ternary with functions19let canAccess = userRole === "admin" ? getAdminContent() : getRegularContent();
Type Operators
JavaScript includes operators to check types and structures.
1// typeof operator2console.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"1011// instanceof operator (checks if an object is an instance of a class)12let arr = [1, 2, 3];13console.log(arr instanceof Array); // true1415let date = new Date();16console.log(date instanceof Date); // true1718// Better way to check for arrays19console.log(Array.isArray(arr)); // true20console.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.
1// Bitwise operators (work on binary representation of numbers)2let a = 5; // binary: 1013let b = 3; // binary: 01145console.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: -69console.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).
1// Operator precedence examples2let result = 2 + 3 * 4; // 14, not 20 (multiplication happens first)3let result2 = (2 + 3) * 4; // 20 (parentheses override default precedence)45// Multiple operators6let x = 5;7let y = 10;8let z = 15;910let result3 = x + y * z; // 15511let result4 = x + y > z && z > y; // false (comparison happens before logical AND)1213// When in doubt, use parentheses for clarity14let result5 = (x + y) > z && (z > y); // false, but clearer intention
Practice Exercises
Try these exercises to reinforce your understanding of JavaScript operators:
// 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 moreLearn about conditional statements and loops in JavaScript.
Learn moreLearn how to create and use functions in JavaScript.
Learn more