An operator in a programming language is a symbol that tells the compiler or interpreter to perform specific mathematical, relational or logical operation and produce final result. For example, the addition (+) symbol is an operator that tells JavaScript engine to add two variables or values. There are following operators are used in JavaScript.
The arithmetic operators are used to perform common arithmetical operations, such as addition, subtraction, multiplication etc.
Example of Code
<p id="demo"></p>
<script>
var x = 5;
var y = 2;
var z = x + y;
document.getElementById("demo").innerHTML = z;
</script>
Output
The assignment operators are used to assign values to variables.
Example of Code
<p id="demo"></p>
<script>
var x = 10;
document.getElementById("demo").innerHTML = x;
</script>
Output
There are two operators which can also used be for strings.
Example of Code
<script>
var str1 = "Hello";
var str2 = " World!";
document.write(str1 + str2 + "<br>"); // Outputs: Hello World!
</script>
Output
The increment/decrement operators are used to increment/decrement a variable's value.
Example of Code
<script>
var x; // Declaring Variable
x = 10;
document.write(++x); // Prints: 11
document.write("<p>" + x + "</p>"); // Prints: 11
</script>
Output
The logical operators are typically used to combine conditional statements.
Example of Code
<script>
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.");
}
</script>
Output
The comparison operators are used to compare two values in a Boolean fashion.
Example of Code
<script>
var x = 25;
var y = "25";
document.write(x == y); // Prints: true
document.write("<br>");
document.write(x === y); // Prints: false
document.write("<br>");
document.write(x != y); // Prints: true
document.write("<br>");
</script>
Output
