Operators
The different type of operators are:
- Assignment operator
- Arithmetic operator
- Increment and Decrement
- Comparison operator
- Logical operator
Assignment Operator
Assignment operator is used to assign a value to a variable. It can be used for multiple assigns together.
var name = "Savic";
var checked = true;
var x = (y = z = 10);
Arithmetic Operators
Arithmetic operators are basically arithmetic operations like addition(+), subtraction(-),division(/), multiplication(*), and modulus(%).
var x = 3;
var y = 5;
var sum = x + y; // value of sum = 8
var sub = x - y; // value of sub = -2
var mul = x * y; // value of mul = 15
var div = x / y; // value of div = 0.6
+ operator can be also used for string concatenation. So, when operating with string, there will be change for string concatenation.
var value1 = "5" + 5; // value of value1 = 55
var value2 = +"5" + 5; // value of value2 = 10
The condition is that the interpreter will always do string concatenation when any of the operands is a string while using the + operator. To avoid this problem put a + at the beginning of the expression.
In another case
var string1 = "Hello";
var number1 = 10;
var number2 = 11;
var string2 = "World";
var result1 = string1 + number1 + number2 + string2;
console.log(result1); // result1 is Hello1011World
var result2 = number1 + number2 + string2;
console.log(result2); // result2 is 21World
var result3 = "" + number1 + number2 + string2;
console.log(result3); // result3 is 1011World
##Increment and Decrement
The ++ is used for increment and -- for decrement.
var x = 2;
x--; // Value of x is decremented to 1
x++; // Value of x is incremented to 2
Pre and Post Increment
- In pre increment, value is incremented by 1 and then the value is assigned.
- In post increment, value is assigned and then the value incremented by 1 .
// In pre increment
var x = 5;
console.log(x++); // Value of x is 5
console.log(x); // Value of x is 6
// In post increment
var x = 5;
console.log(++x); // Value of x is 6
console.log(x); // Value of x is 6
Comparison Operators
Comparison operators are used to evaluate a given statement is true or false. Types of comparison operators are less than (<), less than or equal to (<=), greater than(>), greater than or equal to(>=), not equal to(!=), equal to(==).
var x = 11;
var y = 15;
if (x == y) {
console.log("Values are the same");
} else {
console.log("Values are different");
}
In equal to operator(==) does the type conversion and the comparison is based on the value only.
console.log(10 == "10"); // true;
console.log(10 === "10"); // false;
var x;
var y = null;
console.log(x == y); // true;
console.log(x === y); // false
Logical Operators
To implement multiple or complex comparison we use logical operators. Logical operators includes &&(AND), ||(OR) and !(NOT) operators.
var x = 5;
var y = 3;
if (x && y) {
console.log("True");
}