Javascript Operators


JavaScript also includes operators just like other languages. An operator executes several functions on single or various data values and generates a solution.


Example


Adding values and variables:


var x = 3;         // assign the value 3 to x
var y = 6;         // assign the value 6 to y
var z = x + y;     // assign the value 9 to z (3 + 6)

Live Demo!


Assignment Operator


This operator designates a digit to variable.


var x = 13;



Addition Operator


This operator adds integers.


var x = 3;         // assign the value 3 to x
var y = 6;         // assign the value 6 to y
var z = x + y;     // assign the value 9 to z (3 + 6)


Live Demo!


Multiplication Operator


This operator multiplies the integers.


var x = 9;
var y = 8;
var z = x * y;

Live Demo!


Arithmetic Operators

Operator Name Description
+ Addition Adds two values.
- Subtraction Subtracts two values.
* Multiplication Multiplies two values.
/ Division Adds two values.
% Modulus Permits remainder of a number division.
++ Increment Increases the value of numbers by one.
-- Decrement Decreases the value of numbers by one.


JAVASCRIPT COMPARISON AND LOGICAL OPERATORS


Comparison and logical operators are used to check if something is true or false.


Comparison Operators


Lets say that we have a variable x = 8. The example column is applied on x. Following are the comparison operators:

Operator Description Example
== Equal to x == 9 (false)
x == 8 (true)
x == “8” (true)
=== Both value and type equal x === 8 (true)
x === “8” (false)
!= Not equal x != 5 (true)
!== Both value and type not equal x !== “8” (true)
x !== 8 (false)
> Greater than x > 5 (true)
< Less than x < 10 (true)
>= Greater than or equal to x >= 8 (true)
<= Less than or equal to x <= 3 (false)

The comparison operators can be used in conditional if-else statements to execute code according to which condition is true or false.



let eggs = 12;
if (eggs > 0) {
  document.getElementById("eggs").innerHTML = "You have eggs!";
} else {
  document.getElementById("eggs").innerHTML = "No eggs left. Order more!";
}

Live Demo!


Logical Operators


Logical operators can be used for logic between variables and values.

Lets say that we have a variable x = 8. The example column is applied on x. Following are the logical operators:

Operator Description Example
&& AND (x > 8 && x < 15) false
|| OR (x > 8 || x < 15) true
! NOT !(x == 5) false

Ternary Conditional Operator


The ternary operator is used to assign value to variable according to a condition.


let eggs = 0;
let eggsAvailable = eggs > 0 ? "Available" : "Not Available"; //Not available is stored in the variable

Live Demo!