JavaScript – Operators
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: 15Code language: JavaScript (javascript)
Subtraction (-)
The subtraction operator (-) subtracts the right operand from the left operand:
let num1 = 10;
let num2 = 5;
let difference = num1 - num2; // Result: 5Code language: JavaScript (javascript)
Multiplication (*)
Multiplication (*) is used to multiply two numbers:
let num1 = 10;
let num2 = 5;
let product = num1 * num2; // Result: 50Code language: JavaScript (javascript)
Division (/)
Division (/) divides the left operand by the right operand:
let num1 = 10;
let num2 = 5;
let quotient = num1 / num2; // Result: 2Code language: JavaScript (javascript)
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: 1Code language: JavaScript (javascript)
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: trueCode language: JavaScript (javascript)
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: falseCode language: JavaScript (javascript)
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)Code language: JavaScript (javascript)
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: trueCode language: JavaScript (javascript)
Greater Than or Equal To (>=)
Verifies if one value is greater than or equal to another.
let isGreaterOrEqual = num1 >= num2; // isGreaterOrEqual will be true
Code language: JavaScript (javascript)
Less Than or Equal To (<=):
Determines if one value is less than or equal to another.
let isLessOrEqual = num1 <= num2; // isLessOrEqual will be false
Code language: JavaScript (javascript)
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: trueCode language: JavaScript (javascript)
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: trueCode language: JavaScript (javascript)
Logical NOT (!)
The logical NOT operator (!) negates a boolean value:
let isActive = true;
let isInactive = !isActive; // Result: falseCode language: JavaScript (javascript)
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;Code language: JavaScript (javascript)
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: 8Code language: JavaScript (javascript)
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: 15Code language: JavaScript (javascript)
Multiplication Assignment (*=):
Multiplies the variable’s current value by a value and assigns the result.
x *= 2; // x is now 24
Code language: JavaScript (javascript)
Division Assignment (/=):
Divides the variable’s current value by a value and assigns the result.
x /= 4; // x is now 6
Code language: JavaScript (javascript)
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: 4Code language: JavaScript (javascript)
Decrement (--)
The decrement operator (--) subtracts 1 from a variable:
let tickets = 10;
tickets--; // Result: 9Code language: JavaScript (javascript)
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) = 001Code language: JavaScript (javascript)
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) = 111Code language: JavaScript (javascript)
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) = 110Code language: JavaScript (javascript)
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)Code language: JavaScript (javascript)
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 = 10100Code language: JavaScript (javascript)
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 = 100Code language: JavaScript (javascript)
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 = 00111111111111111111111111111100Code language: JavaScript (javascript)
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 : expressionIfFalseCode language: JavaScript (javascript)
- 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.";Code language: JavaScript (javascript)
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"Code language: JavaScript (javascript)
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 variableCode language: JavaScript (javascript)
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"Code language: JavaScript (javascript)
- Strings:
let name = "Alice";
typeof name; // Returns "string"Code language: JavaScript (javascript)
- Booleans:
let isStudent = true;
typeof isStudent; // Returns "boolean"Code language: JavaScript (javascript)
- Objects:
let person = {
firstName: "John",
lastName: "Doe"
};
typeof person; // Returns "object"Code language: JavaScript (javascript)
- Arrays:
let colors = ["red", "green", "blue"];
typeof colors; // Returns "object"Code language: JavaScript (javascript)
- Functions:
function greet(name) {
console.log("Hello, " + name + "!");
}
typeof greet; // Returns "function"Code language: JavaScript (javascript)
- Undefined:
let jobTitle;
typeof jobTitle; // Returns "undefined"Code language: JavaScript (javascript)
- Null:
let emptyValue = null;
typeof emptyValue; // Returns "object" (historical quirk in JavaScript)Code language: JavaScript (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.
