Lesson 6 of 36 · 7 min
Operators
Explore JavaScript operators with clear examples. Learn how to perform calculations, make comparisons, and manipulate data in your JavaScript code…
On this page
- Arithmetic Operators
- Addition (+)
- Subtraction (-)
- Multiplication (*)
- Division (/ )
- Modulus (% )
- Comparison Operators
- Greater Than (>)
- Less Than (<)
- Equal To (=== )
- Not Equal To (!== )
- Greater Than or Equal To (>=)
- Less Than or Equal To (<=):
- Logical Operators
- Logical AND (&& )
- Logical OR (||)
- Logical NOT (!)
- Assignment Operators
- Assignment (=)
- Addition Assignment (+= )
- Subtraction Assignment (-=)
- Multiplication Assignment (*=):
- Division Assignment (/=):
- Increment and Decrement Operators
- Increment (++ )
- Decrement (-- )
- Bitwise Operators :
- Conditional (Ternary) Operator
- String Concatenation
- typeof Operator
- Conclusion
JavaScript operators are the building blocks of any JavaScript program. They enable you to perform actions on variables and values, make decisions in your code, and manipulate data. Whether you’re a beginner or an experienced developer, a solid grasp of these operators is crucial for effective JavaScript programming. In this blog post, we’ll explore the most common JavaScript operators and provide clear examples for each.
Arithmetic Operators
Let’s begin with arithmetic operators. These symbols perform basic mathematical calculations, such as addition, subtraction, multiplication, division, and modulus (remainder). Consider the following examples:
Addition (+)
The addition operator (+) is used to add two numbers together:
let num1 = 10;
let num2 = 5;
let sum = num1 + num2; // Result: 15
Subtraction (-)
The subtraction operator (-) subtracts the right operand from the left operand:
let num1 = 10;
let num2 = 5;
let difference = num1 - num2; // Result: 5
Multiplication (*)
Multiplication (*) is used to multiply two numbers:
let num1 = 10;
let num2 = 5;
let product = num1 * num2; // Result: 50
Division (/)
Division (/) divides the left operand by the right operand:
let num1 = 10;
let num2 = 5;
let quotient = num1 / num2; // Result: 2
Modulus (%)
The modulus operator (%) returns the remainder when the left operand is divided by the right operand:
let num1 = 10;
let num2 = 3;
let remainder = num1 % num2; // Result: 1
Comparison Operators
Comparison operators help you compare values and return Boolean results (true or false). They include equality (===), inequality (!==), greater than (>), less than (<), greater than or equal to (>=), and less than or equal to (<=).
Greater Than (>)
The greater-than operator (>) checks if the left operand is greater than the right operand:
let age = 25;
let isAdult = age > 18; // Result: true
Less Than (<)
The less-than operator (<) checks if the left operand is less than the right operand:
let score = 80;
let passingScore = score < 70; // Result: false
Equal To (===)
The equal-to operator (===) checks if the values on both sides are equal:
let num1 = 5;
let num2 = "5";
let isEqual = num1 === num2; // Result: false (strict equality)
Not Equal To (!==)
The not-equal-to operator (!==) checks if the values on both sides are not equal:
let a = 10;
let b = 20;
let isNotEqual = a !== b; // Result: true
Greater Than or Equal To (>=)
Verifies if one value is greater than or equal to another.
let isGreaterOrEqual = num1 >= num2; // isGreaterOrEqual will be true
Less Than or Equal To (<=):
Determines if one value is less than or equal to another.
let isLessOrEqual = num1 <= num2; // isLessOrEqual will be false
Logical Operators
Logical operators are used to manipulate boolean values. Here are the primary logical operators:
Logical AND (&&)
The logical AND operator (&&) returns true if both operands are true:
let isStudent = true;
let hasJob = false;
let canApply = isStudent && !hasJob; // Result: true
Logical OR (||)
The logical OR operator (||) returns true if at least one operand is true:
let isMember = true;
let hasCoupon = false;
let discountAvailable = isMember || hasCoupon; // Result: true
Logical NOT (!)
The logical NOT operator (!) negates a boolean value:
let isActive = true;
let isInactive = !isActive; // Result: false
Assignment Operators
Assignment operators are used to assign values to variables and update variable values. Here are some common assignment operators:
Assignment (=)
The assignment operator (=) assigns a value to a variable:
let x = 10;
Addition Assignment (+=)
The addition assignment operator (+=) adds a value to a variable and assigns the result back to the variable:
let count = 5;
count += 3; // Equivalent to count = count + 3; Result: 8
Subtraction Assignment (-=)
The subtraction assignment operator (-=) subtracts a value from a variable and assigns the result back to the variable:
let total = 20;
total -= 5; // Equivalent to total = total - 5; Result: 15
Multiplication Assignment (*=):
Multiplies the variable’s current value by a value and assigns the result.
x *= 2; // x is now 24
Division Assignment (/=):
Divides the variable’s current value by a value and assigns the result.
x /= 4; // x is now 6
Increment and Decrement Operators
Increment and decrement operators are used to increase or decrease the value of a variable by 1:
Increment (++)
The increment operator (++) adds 1 to a variable:
let counter = 3;
counter++; // Result: 4
Decrement (--)
The decrement operator (--) subtracts 1 from a variable:
let tickets = 10;
tickets--; // Result: 9
Bitwise Operators :
Bitwise operators in JavaScript allow you to manipulate the individual bits (0s and 1s) of binary representations of numbers. They are not as commonly used as arithmetic or comparison operators but can be quite powerful in specific situations where you need to work at a low-level binary level. Here are the main bitwise operators:
1. Bitwise AND (&): This operator performs a bitwise AND operation on each pair of corresponding bits. It returns 1 only if both bits being compared are 1; otherwise, it returns 0.
let result = 5 & 3; // Result is 1 because in binary: 5 (101) & 3 (011) = 001
2. Bitwise OR (|): The bitwise OR operator returns 1 if at least one of the bits being compared is 1.
let result = 5 | 3; // Result is 7 because in binary: 5 (101) | 3 (011) = 111
3. Bitwise XOR (^): The XOR (exclusive OR) operator returns 1 if exactly one of the bits being compared is 1.
let result = 5 ^ 3; // Result is 6 because in binary: 5 (101) ^ 3 (011) = 110
4. Bitwise NOT (~): This unary operator inverts all the bits of a number. It changes 0s to 1s and vice versa.
let result = ~5; // Result is -6 because in binary: ~5 (110) = -6 (110)
Note: The result is a 32-bit signed integer. Negative numbers are represented using Two’s complement notation.
5. Left Shift (<<): The left shift operator shifts the bits of a number to the left by a specified number of positions, filling in with zeros from the right.
let result = 5 << 2; // Result is 20 because in binary: 5 (101) << 2 = 10100
6. Right Shift (>>): The right shift operator shifts the bits of a number to the right by a specified number of positions. If the number is positive, it fills in with zeros from the left. If it’s negative, it fills in with ones.
let result = 16 >> 2; // Result is 4 because in binary: 16 (10000) >> 2 = 100
7. Zero-fill Right Shift (>>>): Similar to the right shift operator, but it always fills in with zeros from the left, even if the number is negative.
let result = -16 >>> 2; // Result is 1073741820 because in binary: -16 (11111111111111111111111111110000) >>> 2 = 00111111111111111111111111111100
Bitwise operators are primarily used in scenarios where you need to work with binary data, optimize code for specific hardware, or perform low-level data manipulation. They are not commonly used in everyday JavaScript programming but can be valuable in certain specialized applications.
Conditional (Ternary) Operator
The conditional operator in JavaScript, often referred to as the ternary operator, is a handy way to write concise conditional statements. It provides a compact alternative to the traditional if-else statement, allowing you to make decisions and assign values based on a condition in a single line of code.
Here’s how the conditional operator works:
condition ? expressionIfTrue : expressionIfFalse
- The
conditionis the test that you want to evaluate, which should result in eithertrueorfalse. - If the
conditionistrue, theexpressionIfTrueis executed. - If the
conditionisfalse, theexpressionIfFalseis executed.
Let’s look at a practical example:
let age = 18;
let canVote = age >= 18 ? "Yes, you can vote!" : "Sorry, you cannot vote.";
In this example, we’re using the ternary operator to determine whether a person age is 18 or older. If the condition age >= 18 is true, the message “Yes, you can vote!” is assigned to the canVote variable. If the condition is false, the message “Sorry, you cannot vote.” is assigned.
The ternary operator is particularly useful when you need to assign a value to a variable based on a simple condition. It can make your code more concise and easier to read, but it’s essential to use it judiciously to maintain code clarity and readability.
String Concatenation
The + operator can also be used for string concatenation, which combines two or more strings:
let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName; // Result: "John Doe"
typeof Operator
The typeof operator in JavaScript is a useful tool for determining the data type of a value or variable. It allows you to inspect and check the type of data you’re working with, which can be particularly helpful in situations where you need to handle data dynamically. Here’s how the typeof operator works:
typeof variable
typeof: This is the keyword that starts the operator.variable: This is the value or variable you want to check.
Here are some common data types and how the typeof operator can be used with them:
- Numbers:
let age = 30;
typeof age; // Returns "number"
- Strings:
let name = "Alice";
typeof name; // Returns "string"
- Booleans:
let isStudent = true;
typeof isStudent; // Returns "boolean"
- Objects:
let person = {
firstName: "John",
lastName: "Doe"
};
typeof person; // Returns "object"
- Arrays:
let colors = ["red", "green", "blue"];
typeof colors; // Returns "object"
- Functions:
function greet(name) {
console.log("Hello, " + name + "!");
}
typeof greet; // Returns "function"
- Undefined:
let jobTitle;
typeof jobTitle; // Returns "undefined"
- Null:
let emptyValue = null;
typeof emptyValue; // Returns "object" (historical quirk in JavaScript)
Using the typeof operator, you can make decisions in your code based on the data type of a value. For example, you might want to perform different actions or validations depending on whether a variable is a number, a string, or something else. It’s a handy tool for writing more flexible and dynamic JavaScript code.
Conclusion
JavaScript operators are essential tools for performing a wide range of operations in your code. By understanding and effectively using these operators, you’ll be better equipped to write JavaScript programs that manipulate data, make decisions, and achieve the desired functionality. Practice and experimentation are key to mastering the art of using operators in JavaScript, so don’t hesitate to try out different scenarios and examples to deepen your understanding.
More from JavaScript Tutorial
- Lesson 8 · 3 minSwitch CaseExplore the power of JavaScript’s switch case statement in decision-making with practical examples and use cases in this comprehensive guide
- Lesson 9 · 2 minWhile LoopExplore the JavaScript while loop, a fundamental construct for automating tasks based on conditions. Learn its syntax and common use cases
- Lesson 10 · 2 minFor LoopExplore the JavaScript for loop: a versatile construct for automating repetitive tasks, iterating through arrays, and data processing.