Javascript Operators

Javascript Operators

JavaScript operators are symbols that are used to perform operations on operands (data value). For example,

2 + 3; // 5

Here + sign is an operator and 2 is the left side operand and 3 is the right side operand.

//syntax

<Left operand> operator <right operand>

<Left operand> operator

Javascript Operator types

JavaScript includes the following categories of operators.

  • Arithmetic Operators
  • Comparison Operators
  • Logical Operators
  • Assignment Operators
  • Conditional Operators
  • Ternary Operator

Arithmetic Operators:

Arithmetic operators are used to perform mathematical operations between numeric operands.

const sumOfNumbers = 2 + 3;  //5

Here's a list of commonly used Arithmetic operators: Arithmetic.png

Comparison Operators:

JavaScript provides comparison operators that compare two operands and return a boolean value true or false.

const a = 10, b = 5;
console.log(a > b); // true

In this example, the comparison operator > is used to compare whether a is greater than b. Comparison.png

Logical Operators:

In JavaScript, the logical operators are used to combine two or more conditions. An interesting point to note about logical operators AND and OR is that they do not return a boolean but the value of one of the two operands instead (truthy value).

Consider the following example, one would assume that the value of conditionPassed to be a boolean but what this code is returning is 2

  const a = 1 , b = 2; 
  const conditionPassed = a && b 

//more examples
'abc' && 'def'  && 'xyz'   // returns 'xyz'
'abc' && 0 && 'xyz' && false  // returns 0
false && 0 && 'xyz' && 'abc'  // returns false

Similarly, OR operator will start determining whether operand1 is truthy or falsy. If it is truthy it will return the value of operand1 otherwise, it will continue to check the next operand until it finds the first truthy value

1 || 2 // returns 1
1 || 2 || 3 || 4 || 5   // returns 1
'' || 0 || false || 'yes'   // returns 'yes'

Logical.png

Assignment Operators:

JavaScript provides the assignment operators to assign values to variables with fewer keystrokes.

const a = 7;

Here, the = operator is used to assign value 7 to variable a.

Assignment.png

Ternary Operator:

JavaScript provides an operator called ternary operator :? that assigns a value to a variable based on some condition. This is the short form of the if-else condition.

const  a = 10, b = 5;

let c = a > b? a : b; // value of c would be 10
let d = a > b? b : a; // value of d would be 5

String Concatenation:

The + operator performs a concatenation operation when one of the operands is of string type. Consider the following example

const  a = 10, b = "Hello ", c = "World!", d = 5;

a + b; //returns "10Hello "

b + c; //returns "Hello World!"

a + d; //returns 15

b + true; //returns "Hello true"

c - b; //returns NaN; - operator can only used with numbers