JS Operators

HTML
CSS
C#
SQL

Operators in JavaScript

Operators in JavaScript are symbols or keywords that instruct the JavaScript engine to execute specific actions. For instance, the addition (+) symbol serves as an operator, prompting the JavaScript engine to add two variables or values. Similarly, operators like equal-to (==), greater-than (>), or less-than (<) are used to direct the JavaScript engine to compare two variables or values. These operators play a crucial role in performing various operations within JavaScript code.

Here’s a various types of operators in JavaScript:

1. Arithmetic Operators

Arithmetic operators enable the execution of common mathematical operations, such as addition, subtraction, multiplication, and more. Here’s a comprehensive list of these operators:

The following example will show you these arithmetic operators in action:

Example :

See the Pen Arithmetic Operators by Training Course (@Training-Course) on CodePen.

In this example:

x + y adds the values of x and y, resulting in 14.
x – y subtracts the value of y from x, resulting in 6.
x * y multiplies the values of x and y, resulting in 40.
x / y divides the value of x by y, resulting in 2.5.
x % y calculates the remainder when x is divided by y, resulting in 2.

Incrementing and Decrementing Operators

The increment (`++`) and decrement (`–`) operators are used to adjust the value of a variable.

The following example will show you how increment and decrement operators work:

– `++x` increments the value of `x` before using it, resulting in `11`.

– `x++` uses the current value of `x` and then increments it, resulting in `10`.

– `–x` decrements the value of `x` before using it, resulting in `9`.

– `x–` uses the current value of `x` and then decrements it, resulting in `10`.

Assignment Operators

Assignment operators are employed to assign values to variables, facilitating various operations like simple assignment, addition assignment, subtraction assignment, multiplication assignment, and division assignment.

Here’s an example demonstrating these assignment operators in action:

  var x; // Declaring Variable

  x = 10;
  document.write(x); // Outputs: 10

  x = 20;
  x += 30;
  document.write(x); // Outputs: 50

  x = 50;
  x -= 20;
  document.write(x); // Outputs: 30

  x = 5;
  x *= 25;
  document.write(x); // Outputs: 125

  x = 50;
  x /= 10;
  document.write(x); // Outputs: 5

  x = 100;
  x %= 15;
  document.write(x); // Outputs: 10

In this example:

– `x += 30` is equivalent to `x = x + 30`, resulting in `50`.

– `x -= 20` is equivalent to `x = x – 20`, resulting in `30`.

– `x *= 25` is equivalent to `x = x * 25`, resulting in `125`.

– `x /= 10` is equivalent to `x = x / 10`, resulting in `5`.

– `x %= 15` is equivalent to `x = x % 15`, resulting in `10`.

Logical Operators

Logical operators in JavaScript are commonly used to combine conditional statements.

Here's an example illustrating how these logical operators work:

var year = 2018;

// Leap years are divisible by 400 or by 4 but not 100

if ((year % 400 == 0) || ((year % 100 != 0) && (year % 4 == 0))) {
document.write(year + ” is a leap year.”);
} else {
  document.write(year + ” is not a leap year.”);
}

In this example:

– `year % 400 == 0` checks if the year is divisible by 400.
– `year % 100 != 0` checks if the year is not divisible by 100.
– `year % 4 == 0` checks if the year is divisible by 4.

The logical operators used are `||` (OR) and `&&` (AND), combining these conditions to determine if the given year is a leap year or not.

String Operators in JavaScript

In JavaScript, two operators can be used for manipulating strings:

JavaScript Comparison Operators

Comparison operators in JavaScript are used to compare two values and return a Boolean result.

var x = 25;
var y = 35;
var z = “25”;

document.write(x == z);  // Outputs: true
document.write(x === z); // Outputs: false
document.write(x != y);  // Outputs: true
document.write(x !== z); // Outputs: true
document.write(x < y);   // Outputs: true
document.write(x > y);   // Outputs: false
document.write(x <= y);  // Outputs: true
document.write(x >= y);  // Outputs: false

In this example:

– `==` checks if the values are equal, regardless of their types (`true` because the values are equal after type coercion).
– `===` checks if the values are equal and of the same type (`false` because the values are of different types).
– `!=` checks if the values are not equal (`true` because the values are not equal).
– `!==` checks if the values are not equal or not of the same type (`true` because the values are of different types).
– `<` checks if the left operand is less than the right operand (`true` because 25 is less than 35).
– `>` checks if the left operand is greater than the right operand (`false` because 25 is not greater than 35).
– `<=` checks if the left operand is less than or equal to the right operand (`true` because 25 is less than 35).
– `>=` checks if the left operand is greater than or equal to the right operand (`false` because 25 is not greater than 35).

These operators are fundamental for making decisions and controlling the flow of your JavaScript programs.

Ternary Operator

The ternary operator, also known as the conditional operator, provides a concise way of writing an if-else statement in JavaScript. It consists of three operands: a condition to be evaluated, an expression to be executed if the condition is true, and an expression to be executed if the condition is false.

The syntax of the ternary operator is as follows:

  condition ? expressionIfTrue : expressionIfFalse;

Here’s an example demonstrating how the ternary operator can be used to assign a value to a variable based on a condition:

  let age = 25;
  let allowed = age >= 18 ? “Yes” : “No”;
  document.write(allowed); // Outputs: “Yes

In this example, if the condition `age >= 18` is true, the value “Yes” is assigned to the variable `allowed`; otherwise, the value “No” is assigned. The ternary operator is a concise and expressive way to handle simple conditional assignments in JavaScript.

Course Video

Examples for Practice

You have to solve all the questions given below in the editor without copy-pasting.

1. Write a js program to check a = 10 is greater than b = 15 if it is greater than b then print “a is greater than b” and if b is greater than a then print “b is greater than a “.

The task is to write a JavaScript program that checks whether the value of the variable a (which is initialized as 10) is greater than the value of the variable b (which is initialized as 15). Depending on the result of this comparison, the program should print different messages.
1. Variables Initialization: a = 10 and  b = 15.
2. Comparison and Output:
– The program uses an if statement to check if the value of a is greater than the value of b (if (a > b)).
– If the condition is true, the program prints the message “a is greater than b”.
– If the condition is false, it uses an else if statement to check if the value of b is greater than the value of a (else if (b > a)).
– If this condition is true, the program prints the message “b is greater than a”.
– If both conditions are false, it means that a and b are equal, so the program prints the message “a and b are equal”.
3. Console Output: Depending on the values of a and b, the program will print messages to the console.

Here’s a simple JavaScript program that checks if a is greater than b and prints the appropriate message:

// Given variables
var a = 10;
var b = 15;

// Check if a is greater than b
if (a > b) {
console.log(“a is greater than b”);
} else if (b > a) {
console.log(“b is greater than a”);
} else {
console.log(“a and b are equal”);
}

Output

2. Write a program that takes two numbers using a prompt and performs arithmetic operations using different arithmetic operators (+, -, *, /, %) and displays the results on a document in the <H5> tag.

The task is to write a JavaScript program that interacts with the user by using the prompt method to input two numbers. After obtaining the user’s input, the program should perform various arithmetic operations (addition, subtraction, multiplication, division, and modulo) on those numbers and display the results on an HTML document inside an <h5> tag.
1. Use the prompt() method to obtain two numbers from the user, which are stored in the variables num1 and num2.
2. Perform various arithmetic operations (addition, subtraction, multiplication, division, and remainder) on the input numbers.
3. Display the results of these operations on the document using document.write(), with each result presented within <h5> tags for better formatting.

Here’s a JavaScript program that takes two numbers, performs various arithmetic operations, and displays the results on the document:

// Prompt the user to enter two numbers
var firstNumber = parseFloat(prompt(“Enter the first number:”));
var secondNumber = parseFloat(prompt(“Enter the second number:”));

// Perform arithmetic operations
var additionResult = firstNumber + secondNumber;
var subtractionResult = firstNumber – secondNumber;
var multiplicationResult = firstNumber * secondNumber;
var divisionResult = firstNumber / secondNumber;
var modulosResult = firstNumber % secondNumber;

// Display the results on the HTML document
document.write(“<h5>Addition Result: ” + additionResult + “</h5>”);
document.write(“<h5>Subtraction Result: ” + subtractionResult + “</h5>”);
document.write(“<h5>Multiplication Result: ” + multiplicationResult + “</h5>”);
document.write(“<h5>Division Result: ” + divisionResult + “</h5>”);
document.write(“<h5>Modulos Result: ” + modulosResult + “</h5>”);

Output

3. Write a program that uses various assignment operators (+=, -=, *=, /=) to modify the value of a variable and display the updated value.

The task is to write a JavaScript program that starts with an initial value of 10 and then uses different assignment operators to modify this value. After each modification, the program should display the updated value.
1. Start with an Initial Value:
Set a variable named x with an initial value of 10.
2. Modify the Value using Assignment Operators:
– Use different assignment operators (+=, -=, *=, /=) to change the value of x in various ways.
– For example, x += 5 adds 5 to the current value of x, x -= 3 subtracts 3, x *= 2 multiplies by 2, and x /= 4 divides by 4.
3. Display the Updated Values:
After each modification, use console.log() to show the new value of x.

Here’s a JavaScript program with an initial value of 10, and it utilizes different assignment operators to modify the value:

// Initial value of the variable
var x = 10;

// Use different assignment operators to modify the value
x += 5; // Equivalent to x = x + 5;
console.log(“After += operation: ” + x);

x -= 3; // Equivalent to x = x – 3;
console.log(“After -= operation: ” + x);

x *= 2; // Equivalent to x = x * 2;
console.log(“After *= operation: ” + x);

x /= 4; // Equivalent to x = x / 4;
console.log(“After /= operation: ” + x);

Output

4. Implement a program that increments and decrements a variable. Display the results.

The task is to write a JavaScript program that increments and decrements a variable and then displays the results.
1. Start with an Initial Value:
Set a variable named myVariable with an initial value of 5.
2. Perform increment and decrement operations on the variable.
– Increment: Use the ++ operator to increase the value of the variable by 1.
– Decrement: Use the — operator to decrease the value of the variable by 1.
3. Display the Results:
After each operation, display the updated value of the variable to the console. 

Here’s a JavaScript program that initializes a variable, increments it, decrements it, and then displays the results:

// Initialize a variable with an initial value
var myVariable = 5;

// Increment the variable
myVariable++;
console.log(“After incrementing: ” + myVariable);

// Decrement the variable
myVariable–;
console.log(“After decrementing: ” + myVariable);

Output

5. Write a program that checks if a number is within a specific range (e.g., between 10 and 20) using && (logical AND) operator.

The task is to write a JavaScript program that checks if a given number is within a specific range. The program should use the && (logical AND) operator to perform this check.
1. Get a Number:
Prompt the user to enter a number.
2. Check Range:
Use the && operator to check if the entered number is both greater than or equal to a lower limit (e.g., 10) and less than or equal to an upper limit (e.g., 20).
3. Display Result: Print a message indicating whether the number is within the specified range or not.

Here’s a JavaScript program that checks if a number is within a specific range (between 10 and 20) using the && (logical AND) operator:

// Prompt user to enter a number
var userInput = parseFloat(prompt(“Enter a number:”));

// Check if the number is within the range (10 to 20)
if (userInput >= 10 && userInput <= 20) {
console.log(“The number is within the range (10 to 20).”);
} else {
console.log(“The number is outside the specified range.”);
}

Output