Operators in Javascript

Comparison Operators

Equality Operators: == vs ===

  • === –> Strict equal to
    • true if the operands are equal and of the same type
  • !== –> Strict not equal to
    • true if the operands are equal but of different type or not equal at all
console.log(18 === 18)  
// true
console.log(18 === '18') 
// false

// == is rarely used in JS
console.log(18 == 18) 
// true
console.log(18 == '18') 
// true

PDF

  • Boolean Operator
  • TernaryOperator
  • Boolean Tricks
        Page: /

The Conditional (Ternary) Operator

const isLogin = true;

// Does not work
const userName = if (isLogin) {
  return ‘Max’;
} else {
  return null;
}

// Works
const userName = isLogin ? 'Max' : null;
console.log(userName);
const age = 23;
const drink = age >= 18 ? 'wine' : 'water';
console.log(drink);
// "wine"

console.log(`I like to drink ${age >= 18 ? 'wine' : 'water'}`);
// "I like to drink wine"

Logical Operators

  • AND(&&), OR(||), NOT(!)
console.log(true && true)  
// true
console.log(true || false)  
// true
console.log(!true)    
// flase
  • Tricks for AND and OR
// If 1st value is false --> returns 2nd value
const userName1 = "" || 'Max'
console.log(userName1)
// Max

// If 1st value is true --> returns 1st value
const userName2 = "John" || 'Max'
console.log(userName2)
// John


// If 1st value is true --> returns 2nd value
const cartCheckout1 = true && "Books"
console.log(cartCheckout1)
// Books

// If 1st value is false --> returns false
const cartCheckout2 = false && ["Books"]
console.log(cartCheckout2)
// false

Assignment operators

let x = 10 + 5;
// 15
x += 10; 
// x = x + 10 = 25
x *= 4; 
// x = x * 4 = 100
x++;  // 101
x--;  // 100
x--;  // 99

Type Operators

  • type –> Returns the type of a variable
  • instanceof –> Returns true if an object is an instance of an object type
let val = 100.1
console.log(typeof val);
// "number"

// length is used only for String
// undefined for others
val = "Amrit"
console.log(val.length);

//toFixed is used only for Numbers
val = 100.30302
console.log(val.toFixed(2)); //100.30

Type Conversion

To String

let val;
val = String(555);  
// "555"
val = String(4+4);  
// "8"
val = String(true);   
// "true"
val = String(new Date());
// "Wed Nov 03 2021 14:57:08 GMT+0530 (India Standard Time)"
val = String([1,2,3,4]);  
// "1,2,3,4"

// Alt Way ==> toString() 
val = (5).toString(); 
// "5"
val = (true).toString();  
// "true"

To Number

val = Number('5');   
// 5
val = Number(true);  
// 1
val = Number(false); 
// 0
val = Number(null);   
// 0
console.log(Number("")) 
// Empty string turns to 0
val = Number('hello');  
// NaN ...Not A Number
val = Number([1,2,3]);  
// NaN

//Alt Way
val = parseInt('100.30');
// 100
val = parseFloat('100.30');
// 100.3

Reference