Modern Operators in JavaScript

Modern Operators in JavaScript

ยท

5 min read

Now that we've covered the basics of JavaScript, Let's take a closer look at modern JavaScript and its built-in data structures.

Destructuring

Destructuring is a basic ES6 feature that allows us to unpack the values of an array or an object into separate variables.

Array destructuring

let arr = [1, 2, 3 ];
let a = arr[0]; // 1
let b = arr[1]; // 2
let c = arr[2]; // 3

This is how we generally unpack the array elements.

Let's learn an easier method to do that.

// Values
let [a, b, c] = [1, 2, 3];
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3

// Array
let arr = [1, 2, 3 ,4, 5];
let [a, b, c, d, e] = arr;
// Now given variables will be assigned
// their respective values from the array

We use square brackets (because it's an array) to write variables and assign either values or an array to them.

let arr = [7, 8, 9];
let [a, ,b] = arr;
console.log(a); // 7
console.log(b); // 9

We can skip a particular element by keeping the variable name empty at desired element's position.

Object destructuring

Destructuring objects is somewhat different from destructuring arrays.

We use curly brackets (because it's an object) and the names of variables should match the names of actual object keys.

const person = {
 firstName : 'John', 
 lastName : 'Doe',
 age : '28',
}

const {firstName, lastName, personAge} = person;
console.log(firstName); // John
console.log(lastName); // Doe
console.log(personAge); // 28

Renaming variables

To change the variable name, we can use a colon ( : ) and rename it.

const {firstName : fName, lastName : lName, personAge : age } = person;

Assigning default values

To assign default values to a variable, we can simply use equals to ( = ) and write desired value.

const {firstName : fName = 'David',
       lastName : lName = 'Smith',
       personAge : age = 30} = person;

Spread And Rest Operator

Spread operator

It is used to expand an array into all its elements using three dots and a variable name. We can use it to copy an array, join two arrays or even separate letters of a string.

Let's consider an array - which has few values. Now, we want to add another array without making it nested. In such cases, the spread operator comes handy.

let arr_1 = [4, 5, 6];
let arr_2 = [1, 2, 3, arr_1];
console.log(arr_2); // [ 1, 2, 3, [4, 5, 6] ]
// This becomes a nested array.

let arr_3 = [0, ...arr_2, ...arr_1]; 
console.log(arr_3); // [0, 1, 2, 3, 4, 5, 6]
// ...arr_2 and ...arr_1 unpacks elements into individual values

let str = 'Hello';
let newStr = [...str];
console.log(newStr); // ['H', 'e', 'l', 'l', 'o'];

Rest operator

It is used to condense multiple values and store them into an array. However, it must be used at the end of the list as it collects all the remaining values.

Let's say we want the first two values of an array and store the rest of the values in an array to use later.

let [a, b, ...others] = [7, 8, 9, 10];
console.log(a); // 7
console.log(b); // 8
console.log(others); // [9, 10]

let newArr = [...others];
console.log(newArr); // [ 9, 10 ]

You must be wondering what just happened ?! We used ...others to collect the values and to expand values as well. Well, spread and rest operators look exactly the same (...name).

The difference is - the spread operator is used on the right side of the assignment operator while the rest operator is used on the left side of the assignment operator.

Short-Circuiting ( && and || )

Up until this point, we have used logical operators only to combine boolean values but we can do a lot more with && and || operators.

OR operator ( || )

Let's see the response of || for numerics and strings.

console.log( 3 || 'John'); // 3
console.log( 0 || 'John'); // John

In case of ||, If the first value is a truthy value, It will immediately return it. Else, the second value will be returned.

console.log( 0 || null || undefined || 'Last'); // Last
console.log( 0 || null || undefined ); // undefined

If multiple operands are provided, It will return the first truthy value found among all of them. If all values are falsy, It will return the last value.

AND operator ( && )

Let's see the response of && operator for numerics and strings.

console.log( 3 && 'John'); // John
console.log( 0 && 'John'); // 0

In case of &&, If the first value is a falsy value, It will immediately return it. Else, the second value will be returned.

console.log( 'First' && 0 && null && undefined); // 0
console.log( '0' && 'null' && 'undefined' ); // undefined

If multiple operands are provided, It will return the first falsy value found among all of them. If all values are truthy, It will return the last value.

Nullish Coalescing Operator

The nullish coalescing operator is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined and otherwise returns its left-hand side operand.

const greet = null ?? 'Hey !';
console.log(greet); // Hey !

const msg = ('Heyyy !' ||  null) ?? 'Hello !';
console.log(msg); // Heyyy

const newMsg = (null || undefined) ?? 'Hello !';
console.log(newMsg); // Hello !

Optional Chaining

The optional chaining operator accesses an object's property or calls a function. If the object accessed or function called using this operator is undefined or null, the expression short circuits and evaluates to undefined instead of throwing an error.

const pet = {
 animal : 'dog',
 dog : {
  name : 'Oreo',
 }
}

const catName = pet.cat?.name;
console.log(catName); // undefined

const dogName = pet.dog?.name;
console.log(dogName); // Oreo

Hope this blog helped you learn a thing or two about modern JavaScript! ๐Ÿ˜„

ย