JavaScript Operators
In JavaScript, operators are special symbols or keywords used to perform operations on values (operands). These operations can range from simple arithmetic to complex logical evaluations. JavaScript has various types of operators that allow you to manipulate variables and values. Let’s explore some of the essential operators in JavaScript and how they work.
Arithmetic Operators
Arithmetic operators enable the execution of common mathematical operations, such as addition, subtraction, multiplication, and more.
Operator | Description | Example | Output |
---|---|---|---|
+ | Addition | let result = 5 + 3; | 8 |
– | Subtraction | let result = 7 – 2; | 5 |
* | Multiplication | let result = 4 * 6; | 24 |
/ | Division | let result = 10 / 2; | 5 |
% | Modulus (Remainder) | let result = 10 % 3; | 1 |
++ | Increment by 1 | let a = 5; a++; | a becomes 6 |
— | Decrement by 1 | let b = 7; b–; | b becomes 6 |
Comparison Operators
In JavaScript, comparison operators are used to define conditions and return a boolean (true or false).
Operator | Description | Example |
---|---|---|
== | Equal to | if (i == 5) |
!= | Not equal to | if (i != 2) |
> | Greater than | if (i > 6) |
< | Less than | if (i < 2) |
>= | Greater than or equal to | if (i >= 2) |
<= | Less than or equal to | if (i <= 3) |
Logical Operators
Logical operators are used to combine conditions and return a boolean value.
Operator | Description | Example |
---|---|---|
&& | Logical AND (both conditions true) | if (person == “male” && age == 21) |
|| | Logical OR (either condition is true) | if (person == “male” || person == “female”) |
! | Logical NOT (negation) | if (person != “male”) |
Conditional (Ternary) Operator
The ternary operator checks a condition and returns a value based on that condition.
Syntax:
condition ? trueResult : falseResult;
Condition | Expression | Explanation | Example | Result |
---|---|---|---|---|
TRUE | condition ? trueResult : falseResult | If the condition is true, the result is trueResult. | 5 > 3 ? “Yes” : “No” | “Yes” |
FALSE | condition ? trueResult : falseResult | If the condition is false, the result is falseResult. | 5 < 3 ? "Yes" : "No" | “No” |
Comparing integers | a > b ? “a is greater” : “b is greater” | Compares two integers and returns a message accordingly. | 10 > 20 ? “10 is greater” : “20 is greater” | “20 is greater” |
Null check | x != null ? x : “null” | Checks if a variable is null. | let str = null; str != null ? str : “null” | “null” |
Even or odd | num % 2 == 0 ? “Even” : “Odd” | Checks if a number is even or odd. | 7 % 2 == 0 ? “Even” : “Odd” | “Odd” |
Age check | age >= 18 ? “Adult” : “Minor” | Determines if a person is an adult or a minor. | let age = 20; age >= 18 ? “Adult” : “Minor” | “Adult” |
Assigning values | let value = isTrue ? 1 : 0; | Assigns a value based on a Boolean condition. | let isTrue = false; let value = isTrue ? 1 : 0; | 0 |
Default value | let result = input ?? “default”; | Uses the nullish coalescing operator to provide a default value if input is null. | let input = null; let result = input ?? “default”; | “default” |
Example: Maximum of Two Numbers
function Maximum() {
let marksofEnglish = 10;
let marksofScience = 20;
let result = marksofEnglish > marksofScience ? marksofEnglish : marksofScience;
console.log(result);
}
Maximum(); // Output: 20
Output
In this example
1. Function Declaration:
function Maximum() {
• This line defines a function named Maximum. Functions are reusable blocks of code that perform a specific task. The code within the curly braces {} will run whenever the function is called.
2. Variable Declarations:
let marksofEnglish = 10; // 1
let marksofScience = 20; // 2
• Two variables are declared using let:
– marksofEnglish is assigned a value of 10.
– marksofScience is assigned a value of 20.
• These variables represent the marks obtained in English and Science subjects, respectively.
3. Ternary Operator:
let result = marksofEnglish > marksofScience ? marksofEnglish : marksofScience; // 3
• This line uses the ternary operator, which is a shorthand way of writing an if-else statement.
• The expression marksofEnglish > marksofScience is evaluated:
– If true (i.e., if marksofEnglish is greater than marksofScience), the value of marksofEnglish will be assigned to the result.
– If false, the value of marksofScience will be assigned to the result.
• In this case, since 10 (marksofEnglish) is not greater than 20 (marksofScience), the result will be assigned the value 20.
4. Logging the Result:
console.log(result); // 4
• This line prints the value of the result to the console. Since the result is 20, it outputs 20 to the console.
5. Function Call:
Maximum(); // Output: 20 // 5
• This line calls the Maximum function, which triggers the execution of all the code within the function.
• When executed, it calculates the maximum of the two numbers and logs 20 to the console.
Example: Age Check
function AgeCheck() {
let age = 20;
let status = age >= 18 ? “Adult” : “Minor”;
console.log(status);
}
AgeCheck(); // Output: Adult
Output
In this example
1. Variable Declaration:
let age = 20;
• A variable age is declared using let and assigned the value 20. This represents the age of a person.
2. Ternary Operator:
let status = age >= 18 ? “Adult” : “Minor”;
• The ternary operator is used to check if the age is greater than or equal to 18.
• The condition age >= 18 is evaluated:
– If true, the status is set to “Adult”.
– If false, the status is set to “Minor”.
• Since the value of age is 20, which is greater than 18, the result will be “Adult”.
3. Logging the Status:
console.log(status);
• This line prints the value of the status variable to the console.
• In this case, the status is “Adult”, so it outputs “Adult” to the console.
4. Function Call:
AgeCheck(); // Output: Adult
• The AgeCheck function is called, triggering the execution of the code within the function.
• The age is checked, and since it’s 20, the function logs “Adult” to the console.
Example: Assigning Values Based on Condition
function AssignValues() {
let privateCustomer = false;
let value = privateCustomer ? 1 : 0;
console.log(value);
}
AssignValues(); // Output: 0
Output
In this example
1. Variable Declaration:
let privateCustomer = false;
• A variable privateCustomer is declared using let and is assigned the value false. This indicates that the customer is not a private customer.
2. Ternary Operator:
let value = privateCustomer ? 1 : 0;
• The ternary operator checks if the value of privateCustomer is true or false.
• The condition privateCustomer is evaluated:
– If true, the value is set to 1.
– If false, the value is set to 0.
• Since privateCustomer is false, the value will be 0.
3. Logging the Value:
console.log(value);
• This line prints the value of the value variable to the console.
• In this case, the value will be 0.
4. Function Call:
AssignValues(); // Output: 0
• The AssignValues function is called, executing the code inside the function.
• Since privateCustomer is false, the ternary operator sets the value to 0, which is then printed to the console.
Example: Assign Default Value
function AssignDefault() {
let input = null;
let result = input ?? “default”;
console.log(result);
}
AssignDefault(); // Output: default
Output
In this example
1. Variable Declaration:
let input = null;
• A variable input is declared using let and is assigned the value null.
• This means that the variable does not contain any meaningful data (i.e., it is null).
2. Nullish Coalescing Operator (??):
let result = input ?? “default”;
• The nullish coalescing operator (??) checks whether the input variable is null or undefined.
• If input is null or undefined, the result is set to “default”.
• If input contains a value (other than null or undefined), that value is assigned to result.
• In this case, since input is null, the result will be assigned the value “default”.
3. Logging the Result:
console.log(result);
• This line prints the value of the result variable to the console.
• In this case, the value of result is “default”, so “default” will be printed.
4. Function Call:
AssignDefault(); // Output: default
• The AssignDefault function is called, which executes the code inside the function.
• Since input is null, the nullish coalescing operator assigns the string “default” to result, and it is printed to the console.
Course Video
YouTube Reference :
1) JavaScript Arithmetic Operators Tutorial in Hindi / Urdu
2) JavaScript Assignment Operators Tutorial in Hindi / Urdu
3) JavaScript Logical Operators Tutorial in Hindi / Urdu
4) JavaScript Comparison Operators Tutorial in Hindi / Urdu
5) JavaScript Conditional Ternary Operator Tutorial in Hindi / Urdu
6) JavaScript Tutorial | JavaScript Operators in English
Practice Scenarios
Scenario 1: Arithmetic Operators
Objective: Use arithmetic operators to perform basic mathematical calculations (addition, subtraction, multiplication, and division).
Expected Output: A console output showing the results of arithmetic operations.
num1= 10, num2 = 5
Output
Scenario 2: Modulus Operator
Objective: Use the modulus operator to find the remainder of the division between two numbers.
Expected Output: A console output showing the remainder of the division.
num1 = 13, num2 = 4
Output
Scenario 3: Comparison Operators
Objective: Use comparison operators (==, ===, !=, >, <, >=, <=) to compare values.
Expected Output: A console output showing the results of different comparisons.
value1 = 10, value2 = “10”
Output
Scenario 4: Logical Operators
Objective: Use logical operators (&&, ||, !) to combine or negate conditions.
Expected Output: A console output showing the results of logical operations.
Code Example:
let isSunny = true;
let hasUmbrella = false;
let goOutside = isSunny && !hasUmbrella;
let canStayDry = isSunny || hasUmbrella;
console.log(`Can Go Outside: ${goOutside}`);
console.log(`Can Stay Dry: ${canStayDry}`);
Output
Scenario 5: Assignment Operators
Objective: Use assignment operators (=, +=, -=, *=, /=) to update the value of a variable.
Expected Output: A console output showing the updated values of the variable.
Code Example:
let count = 10;
count += 5; // count = count + 5;
count -= 2; // count = count – 2;
count *= 3; // count = count * 3;
count /= 2; // count = count / 2;
console.log(`Updated Count: ${count}`);
Code Example:
Scenario 6: Ternary (Conditional) Operator
Objective: Use the ternary operator to decide which value to assign to a variable based on a condition.
Expected Output: A console output showing the result of the conditional evaluation.
age = 18
Code Example:
Scenario 7: Increment and Decrement Operators
Objective: Use the increment (++) and decrement (–) operators to increase or decrease a variable’s value.
Expected Output: A console output showing the value before and after incrementing or decrementing.
number = 5
Scenario 8: Exponentiation Operator
Objective: Use the exponentiation operator (**) to raise a number to a power.
Expected Output: A console output showing the result of exponentiation.
base = 3, exponent = 4
Code Example:
Scenario 9: String Concatenation with Operators
Objective: Use the + operator to concatenate two strings.
Expected Output: A console output showing the concatenated string.
greeting = “Hello”, name = “Alice”
Output
Scenario 10: Bitwise Operators
Objective: Use bitwise operators (&, |, ^, ~, <<, >>) to manipulate bits in numbers.
Expected Output: A console output showing the result of bitwise operations.
num1 = 5, num2 = 3
Operators are symbols or keywords that perform operations on one or more values (operands). For example, +, -, and * are arithmetic operators. Explore these concepts in our JavaScript operators free course video for a better understanding.
JavaScript operators are categorized as:
- Arithmetic Operators (+, -, *, /, %)
- Assignment Operators (=, +=, -=)
- Comparison Operators (==, ===, <, >)
- Logical Operators (&&, ||, !)
- Bitwise Operators (&, |, ^)
- Conditional (Ternary) Operator (condition ? expr1 : expr2)
Learn these categories in detail with our JavaScript operators with free video tutorial designed for beginners.
- == checks for value equality, performing type coercion if necessary.
- === checks for strict equality, comparing both value and type.
For an interactive explanation, watch our free JavaScript operators tutorial for beginners.
The ternary operator evaluates a condition and returns one of two values based on whether the condition is true or false.
Example:
let result = (age >= 18) ? “Adult” : “Minor”;
Learn how to effectively use the ternary operator in our JS operators tutorial free online course.
Logical operators include:
- && (AND): Returns true if both operands are true.
- || (OR): Returns true if at least one operand is true.
- ! (NOT): Negates the value of the operand.
Explore these concepts interactively in our free video tutorial on JavaScript operators for beginners.
Arithmetic operators perform basic mathematical calculations, such as addition (+), subtraction (-), multiplication (*), and division (/). Our JavaScript operators free course video includes practical examples to master these.
Bitwise operators work on binary representations of numbers. Examples include:
- & (AND)
- | (OR)
- ^ (XOR)
- ~ (NOT)
Learn how bitwise operators function with detailed examples in our JavaScript operators with free video tutorial.
Assignment operators assign values to variables. For example:
- = assigns a value.
- += adds and assigns a value.
Example:
let x = 5;
x += 3; // x is now 8
Discover more in our JS operators tutorial free online course.
- The modulus operator returns the remainder of a division operation.
Example:
let remainder = 10 % 3; // Output: 1
Learn the significance of the modulus operator with real-world examples in our JavaScript operators free course video.
Operators like + can concatenate strings.
Example:
let greeting = “Hello” + ” World!”;
console.log(greeting); // Output: Hello World!
Watch our free video tutorial on JavaScript operators for beginners to learn how operators interact with strings.