Operators in JAVA_SCRIPT

Operators in JAVA_SCRIPT

·

2 min read

JavaScript has several types of operators that are used to perform various operations on variables and values. In this blog post, we will be discussing the different types of operators in JavaScript and how they can be used in your code with the help of code snippets.

1. Arithmetic operators:

operators are used to perform mathematical operations on numbers. The most commonly used arithmetic operators are + (addition), - (subtraction), * (multiplication), / (division), and % (modulus).

let num1 = 10;
let num2 = 5;

console.log(num1 + num2); // 15
console.log(num1 - num2); // 5
console.log(num1 * num2); // 50
console.log(num1 / num2); // 2
console.log(num1 % num2); // 0

Comparison operators: These operators are used to compare values and return a Boolean value (true or false). The most commonly used comparison operators are == (equal to), != (not equal to), > (greater than), < (less than), >= (greater than or equal to), and <= (less than or equal to).

let num1 = 10;
let num2 = 5;

console.log(num1 == num2); // false
console.log(num1 != num2); // true
console.log(num1 > num2); // true
console.log(num1 < num2); // false
console.log(num1 >= num2); // true
console.log(num1 <= num2); // false

2. Logical operators:

These operators are used to perform logical operations on Boolean values. The most commonly used logical operators are && (and), || (or), and ! (not).

let num1 = 10;
let num2 = 5;

console.log(num1 > 0 && num2 > 0); // true
console.log(num1 > 0 || num2 > 0); // true
console.log(!(num1 > 0)); // false

3.Assignment operators:

These operators are used to assign a value to a variable. The most commonly used assignment operators are = (assignment), += (addition assignment), -= (subtraction assignment), *= (multiplication assignment), and /= (division assignment).

let num1 = 10;
let num2 = 5;

num1 += num2;
console.log(num1); // 15

num1 -= num2;
console.log(num1); // 10

num1 *= num2;
console.log(num1); // 50

num1 /= num2;
console.log(num1); // 10

4.Ternary operator:

This operator is a shorthand way of writing an if-else statement. The syntax for the ternary operator is (condition) ? (if true) : (if false).

let num1 = 10;
let num2 = 5;

let result = (num1 > num2) ? 'num1 is greater than num2' : 'num2 is greater than num1';
console.log(result); // num1 is greater than num2

5.typeof operator:

This operator returns a string indicating the type of the unevaluated operand.