
October 17, 2023
JavaScript: Modern Operators - Summary with Examples
DESTRUCTURING
#Arrays
const [first, second, third] = ['Nikola', 'Tesla', 'bmw']
Skip a few variables
const [first, , third] = ['Nikola', 'Tesla', 'bmw']
switch variables
let [first,,third] = foodCategories;
console.log(first,third); //Italian Vegetarian
[first,third] = [third,first]
console.log(first,third); //Vegetarian Italian
access array elements deeply
const foodCategories = ['Italian', 'Pizzeria', 'Vegetarian',
[apple juice', 'orange juice'] ]
const [first, , , [aj,oj]] = foodCategories;
console.log(first,aj,oj);//Italian apple juice orange juice
#Object
let {name, title} = {
title: 'John Abraham',
author: 'Mr.'
}
Assign default values
let {name, title, hobbies:{}} = {
name: 'John Abraham',
title: 'Mr.'
}
console.log(hobbies);//{}
Assign other names for variable
let {name:personName, title:personTitle} = {
name: 'John Abraham',
title: 'Mr.'
}
Access the object deeply
let {friday:{open,close}} = {
friday: {
open:11,
close:23
}
}
SPREAD OPERATOR
#Array
const num = [1,2,3];
const newNum = [3,4,...num];
console.log(newNum);//[3, 4, 1, 2, 3]
Copy array
const num = [1,2,3];
const newNum = [...num]//[1,2,3]
Deep copy an array
spread operator only copy first level, not including sub level
const num = [1,2,3];
let newNumbers = JSON.parse(JSON.stringify(num));
Join two arrays
const num1 = [1,2,3];
const num2 = [4,5,6];
const newNum = [...num1,...num2]
console.log(newNum);// [1, 2, 3, 4, 5, 6]
#String
const str = "football";
const letters = [...str,"i","g"];
console.log(letters);// ['f', 'o', 'o', 't', 'b', 'a', 'l', 'l', 'i', 'g']
#Object
Copy Object
const time = {
openTime:11,
closeTime:12
}
const newTime = {...time};
console.log(newTime);//{openTime: 11, closeTime: 12}
Deep copy an Object
spread operator only copy first level, not including sub level
const time = {
openTime:11,
closeTime:12
}
let newObject = JSON.parse(JSON.stringify(time));
REST PATTERN AND PARAMETERS
#Array
//SPREAD, because on RIGHT side of =
const arr = [1,2,...[3,4]];
console.log(arr);
//REST, because its on the left hand side of the =
const [a,b, ...others] = arr;
console.log(others);//[3, 4]
#Object
const openingHours = {
thursDay: {
open: 12,
close: 22,
},
friDay: {
open: 11,
close: 23,
},
saturDay: {
open: 0, // Open 24 hours
close: 24,
},
}
//Objects
const {saturDay, ...weekDays} = openingHours;
console.log(weekDays);//{thursDay: {...}, friDay: {...}}
#Functions
//functions
const add = (...numbers) => {
console.log(numbers);//[4, 5, 6, 7]
}
add(4,5,6,7);
TEMPLATE LITERALS
const firstName = "John";
const lastName = "ABraham";
const birthYear = 1991;
const currentYear = 2023;
const personDetails = `My Name is ${firstName} ${lastName},
a ${(currentYear - birthYear)} years old`;
console.log(personDetails);//My Name is John ABraham, a 32 years old
SHORT CIRCUITING(&& and ||)
#OR(||) operator
console.log("" || 35); //35
console.log(true || 35); //true
console.log(undefined || 35); //35
console.log(null || 35); //35
console.log(undefined || null); //null - undefined is a falsy value
console.log(undefined || 0 || "" || "name"); //name
#AND(&&) operator
console.log("" && 35); //""
console.log(1 && 35); //35
console.log(true && 35); //35
console.log(undefined && 35); //undefined
console.log(null && 35); //null
console.log(undefined && null); //undefined
console.log(undefined && 0 && "" && "name"); //undefined
console.log("name" && 1 && null && "i am here"); //null
THE NULLISH COALESCING OPERATOR(??)
let guests = 0;
console.log(guests || 25);//25
console.log(guests ?? 25);//0
OPTIONAL CHAINING(?.)
let person = {
name:"John",
age:25
}
console.log(person?.job?.title);//undefined-- it will not throw an error
let jobTitle = person?.job?.title ?? "unknown";
console.log(jobTitle);//unknown
LOGICAL ASSIGNMENT OPERATORS
#Logical OR( ||=)
const person = {
name:"john",
job:""
}
person.job ||= "developer"
console.log(person.job); //developer
#Logical AND( &&=)
const person = {
name:"john",
job:"",
followers:5
}
person.followers &&= 30
console.log(person.followers); //30
#Nullish Coalescing(??=)
const person = {
name:"john",
job:"",
followers:0
}
//logical OR assignment consider 0 as falsy value
person.followers||= 30
console.log(person.followers); //30
//nullish assignment consider only null and undefined as falsy value
person.followers ??= 30
console.log(person.followers); //0
ENHANCED OBJECT LITERALS
#Shorthand for initializing Properties
const person = {
name:"John",
age:25,
hobbies:['music','movies','sports']
}
const fullName = "John Abraham"
const age = 25
const hobbies = ['music','movies','sports']
const newPerson = {
fullName,
age,
hobbies
}
#Shorthand for writing Methods
//before ES6
const newPerson = {
fullName,
age,
hobbies,
bornYear:function(){
return 2023 - this.age
}
}
//after ES6
const newPerson = {
fullName,
age,
hobbies,
bornYear(){
return 2023 - this.age
}
}
#Computed Properties
let key = "fullName";
const person = {
[key]:"John"
}
console.log(person.fullName)//John
LOOPING ARRAYS
#for-of
Access only array element
const menu = ['Pizza', 'Coffee', 'Garlic Bread', 'Cake'];
for(const menuItem of menu){
console.log(menuItem);
}
//output
John
Pizza
Coffee
Garlic Bread
Cake
Access array element with index
for(const [index,menuItem] of menu.entries()){
console.log(menuItem+" => "+index);
}
//output
Pizza => 0
Coffee => 1
Garlic Bread => 2
Cake => 3
LOOPING OBJECTS
#Object.keys()
for(const key of Object.keys(person)){
console.log(key);
}
//output
name
age
#Object.values()
for(const key of Object.values(person)){
console.log(key);
}
//output
John
25
#Object.entries()
for(const [key,value] of Object.entries(person)){
console.log(`${key} => ${value}`);
}
//output
name => John
age => 25
EXERCISES
I have attached the github link with examples with answers. I hope it will help you to understand the Javascript Modern Operators concept further.
Next Article(Coming Soon): JavaScript: Working with Strings
Follow me to get more updates regarding JavaScript
230 views