Operators in javascript

? : - conditional operator


let x = a>b ? c : d

//if a>b, x will be equal to c otherwise x will be equal to d

|| operator

?? returns right hand expression if left hand expression is a falsy values - (0, '', NaN, null, undefined)

let qty = 0 || 42;
console.log(qty); //prints 42

?? nullish coalescing

?? returns right hand expression if left hand expression is null or undefined.

const foo = null ?? 'default string';
console.log(foo);

?. - optional chaining operator - Safe navigation operator

When property does not exist on a object, error is not thrown.

let a = {}

console.log(a.n) 
//undefined

console.log(a.n.p)
//VM11422:1 Uncaught TypeError: Cannot read properties of undefined (reading 'p')
   
console.log(a.n?.p)
//undefined

console.log(a?.n?.p)
//undefined

... Rest/Spread operator


function myFunction(x, y, z) { }
let args = [0, 1, 2];
myFunction.apply(null, args);
With spread syntax the above can be written as:

function myFunction(x, y, z) { }
let args = [0, 1, 2];
myFunction(...args);
let obj1 = { foo: 'bar', x: 42 };
let obj2 = { foo: 'baz', y: 13 };

let clonedObj = { ...obj1 };
// Object { foo: "bar", x: 42 }

let mergedObj = { ...obj1, ...obj2 };
// Object { foo: "baz", x: 42, y: 13 }
//Note that Object.assign() triggers setters, whereas spread syntax doesn't.

let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];

arr1 = [...arr2, ...arr1];

== vs ===

== will type cast the operands before doing comparison. But in case of ===, type casting will not happen.

  1=="1"
  //output -> true because even though types are different, values are same

  1==="1"
  //output -> false because types are not matching.
 
  //in case of objects, it returns true if both operands refer to same object. 

Web development and Automation testing

solutions delivered!!