- JS Introduction
- JS Introduction
- JS Comments
- JS Variables
- JS Datatypes
- JS Operators
- JS Type Conversions
- JS Control Flow
- JS Comparisons
- JS If else
- JS If else Ladder
- JS Ternary Operator
- JS Switch
- JS For Loop
- JS For In
- JS For Of
- JS While
- JS Do While
- JS Break & Continue
- JS Functions
- JS Function Declaration
- JS Function Parameters
- JS Return Statement
- JS Function Expressions
- JS Anonymous Functions
- JS Objects
- JS Objects
- JS Object Methods
- JS Object Constructors
- JS Object Destructuring
- JS Object Prototypes
- JS Map, Filter & Reduce
- JS ES6
- JS ES6
- JS let and const
- JS Arrow Functions
- JS Template Literals
- Destructuring Assignment
- JS Spread Operator
- JS Default Parameters
- JS Classes
- JS Inheritance
- JS Map
- JS Set
- JS Async
- JS Callbacks
- JS Asynchronous
- JS Promises
- JS Async/Await
- JS HTML DOM/BOM
- JS Document Object
- JS getElementbyId
- getElementsByClassName
- JS getElementsByName
- getElementsByTagName
- JS innerHTML
- JS outerHTML
- JS Window Object
- JS History Object
- JS Navigator Object
- JS Screen Object
JavaScript Operators
In programming, operators are the building blocks of logic. Think of them as the verbs of the JavaScript language—they allow you to take data (operands) and perform actions like math, comparisons, or logical checks. Understanding operators is the first step toward writing functional code that can make decisions and calculate results.
Operators in JavaScript are symbols that perform operations on operands. Here are the main categories of operators:
Arithmetic Operators
These operators perform arithmetic operations on numeric values. They work just like the math you learned in school, but with a few extra tools for programming tasks like calculating layout widths or handling shopping cart totals.
- Addition (+)
- Subtraction (-)
- Multiplication (*)
- Division (/)
- Modulus (%) - Returns the remainder of a division.
- Exponentiation (**) - Raises a number to a power.
let sum = 5 + 3; // Result: 8
let difference = 10 - 5; // Result: 5
let product = 4 * 6; // Result: 24
let quotient = 20 / 4; // Result: 5
let remainder = 17 % 5; // Result: 2 (Used to check if a number is even or odd)
let power = 2 ** 3; // Result: 8 (2 cubed)
+) is also used for string concatenation. If you add a number and a string, JavaScript will "coerce" the number into a string and join them together (e.g., 5 + "5" results in "55").
%) to determine if a number is even or odd. If number % 2 === 0, the number is even.
Assignment Operators
These operators assign values to variables. While the basic equal sign (=) is the most common, JavaScript provides shorthand versions to update a variable's value based on its current value.
- Assignment (=)
- Addition Assignment (+=)
- Subtraction Assignment (-=)
- Multiplication Assignment (*=)
let x = 10; // Assigns the value 10 to variable x
let y = 5;
y += 3; // Equivalent to: y = y + 3; // Result: 8
let score = 100;
score -= 10; // Useful for decreasing a health bar or countdown; Result: 90
=) with double or triple equals (==/===). Remember: = is for giving a value, while === is for asking if values are the same.
Comparison Operators
These operators compare values and return a boolean result: either true or false. They are the foundation of "if" statements and conditional logic.
- Equal to (==) - Checks value, but ignores data type.
- Strict Equal to (===) - Checks both value and data type (Highly recommended).
- Not Equal to (!=)
- Strict Not Equal to (!==)
- Greater Than (>) and Less Than (<)
console.log(5 == '5'); // true (loose equality: JavaScript converts the string to a number)
console.log(5 === '5'); // false (strict equality: numbers are not strings)
console.log(5 != '5'); // false (loose inequality)
console.log(5 !== '5'); // true (strict inequality)
===) and strict inequality (!==). This prevents bugs caused by JavaScript's "type coercion," making your code more predictable and easier to debug.
Logical Operators
These operators allow you to combine multiple boolean conditions together. They are essential for complex decision-making, such as checking if a user is both logged in and has an active subscription.
- Logical AND (&&) - Returns true if both sides are true.
- Logical OR (||) - Returns true if at least one side is true.
- Logical NOT (!) - Reverses the boolean value (true becomes false).
let isLoggedIn = true;
let hasSubscription = false;
// Example: Gating premium content
if (isLoggedIn && hasSubscription) {
console.log("Welcome to the Premium Lounge!");
}
// Example: Default values
let username = "" || "Guest"; // If the left side is empty/false, it picks "Guest"
if (!hasSubscription) {
console.log("Please subscribe to view this content.");
}
&& operation, if the first part is false, the second part is never even checked, saving processing time.
Increment and Decrement Operators
These operators increase or decrease the value of a variable by exactly one. You will see these used constantly in loops (like for loops) to track iterations.
- Increment (++) and Decrement (--)
let count = 5;
count++; // Increment by 1 (Result: 6)
count--; // Decrement by 1 (Result: 5)
// Real-world: Tracking likes on a post
let likes = 10;
likes++; // User clicked like button
count++ (postfix) and ++count (prefix). Postfix increments the value after the current line is executed, while prefix increments it before. For beginners, it's usually safer to use these on their own lines.
Ternary (Conditional) Operator
This operator provides a concise way to write simple conditional statements. It is the only operator in JavaScript that takes three operands, making it a "one-line if-else."
- Ternary Operator (condition ? valueIfTrue : valueIfFalse)
let age = 20;
let status = (age >= 18) ? 'Adult' : 'Minor';
// Practical example: Setting a CSS class based on state
let theme = isDarkMode ? 'dark-mode' : 'light-mode';
if/else statement instead to keep your code readable for other developers.
These are the fundamental operators that form the core of the JavaScript language. By mastering these, you gain the ability to manipulate data, control the flow of your applications, and build complex logic. Practice using them in small scripts to see how they interact with different data types!