What are operators in JavaScript?
In JavaScript (and programming in general), operators are used to assign or compare values, perform arithmetic operations, evaluate expressions, and more.
JavaScript supports the following operators:
Arithmetic Operators
Arithmetic operators use numeric values as their operands and return a single numerical value.
Comparison Operators
A comparison operator is a binary operator that takes two operands and compares their values.
//arithmetic operatorsconsole.log(2+2);console.log(8*3);console.log(17%3);//comparison operatorsconsole.log(2==2);console.log(2>9);console.log(6>=6);console.log(7<=5);
Logical (or Relational) Operators
A logical operator is used to determine the logic between two expressions. It takes in two operands and produces a single logical value. It returns a Boolean value if used with Boolean operands and vice versa.
For example, the && operator evaluates in the following way:
| Operand 1 | Operand 2 | Result |
|---|---|---|
| True | True | True |
| True | False | False |
| False | True | True |
| False | False | False |
Assignment Operators
An assignment operator is the operator used to provide a new value to the left operand according to the value of the right operand.
Conditional (or Ternary) Operators
Conditional operators are used in evaluating a condition and return a value based on the evaluation of the condition. It is usually used as a shortcut to the if condition.
condition ? exp1 : exp2
It takes three operands and returns the value of exp1 if the condition is true and the value of exp2 if the condition is false.
// logical operatorsconsole.log(true&&true);console.log((2==2)&&false);console.log((2<12)&& (9>=9));//assignment operatorsvar a=5*5;var b=2!=2;console.log(a);console.log(b);a*=2; //multiplying a by 2 and assigning the result to aconsole.log(a);//conditional(ternary operator)var c=(5<2)? "5 is less than 2":"5 is not less than 2.";console.log(c);
Free Resources