JAVASCRIPT DESTRUCTRING AND SHORTHAND HACKS GUIDE
MAHESWAR REDDY(WEB DEVELOPER)
Though it’s almost 6 years back ES6 was released with a great feature destructuring, still some of us using traditional and legacy codes when dealing with objects and array. So this brings me to write a blog on this. In addition to this we will be looking into some javascript shorthand practices.
Destructuring is a JavaScript expression that allows us to extract data from arrays, objects, and maps and set them into new, distinct variables. Destructuring allows us to extract multiple properties, or items, from an array at a time.
When we deal with complex objects in javascript, to read multiple properties in a traditional approach (Prior to ES6) as follows
let employee = {
'Name' : 'David',
'Designation' : 'UI Developer',
'Age' : 30,
}
const employeeName = employee.Name;
const employeeAge = employee.Age;
Just in case, if we need to get more properties we will end up writing lot of code. Thanks to ES6 Destructuring, we can simplify and minimize the code as follows
Syntax: const/let {propertyname}=SourceObject;
Example: const {Name,Age} = employee;
Note: const or let are mandatory in this scenario. Property name should match with source object property name;
Alias Name
To assign existing variables we can use ({..});
Syntax: ({Name} = SourceObject);
Example:
let employeeName;
({Name: employeeName} = employee);
Default values
In some scenarios, we want to check if property is not present in the source object to get default values.
let {Name,Gender:'Male'}=employee;
Nested Object
Let’s consider the employee object contains a nested property as a team.
let employee = {
'Name' : 'David',
'Designation' : 'UI Developer',
'Age' : 30,
'Team' : {
'Name' : 'Rockstars',
'Location' : 'Netherlands'
}
}
To Access Team Name
Let {Team:{Name:teamName}}=employee;
console.log(teamName);
Destructure in Loops
In some cases we need to loop employee names and ages.
const employees = [
{
'name': 'Alex',
'age': 43
},
{
'name': 'Bob',
'age': 53
},
{
'name': 'Carl',
'age': 26
}
];
To loop employee name and age
for(let { name, age } of employees) {
console.log(`${name} is ${age} years old!`);
}
Spread Syntax
Spread syntax helps us clone an object.
The spread operator makes deep copies of data if the data is not nested.For nested objects it will use shallow copy.
We can also expand objects using the spread syntax and copy its enumerable properties to a new object.
Syntax : const clone_some_object = {...some_object}
You can alternatively use object.assign() to create a clone of an object. However, the spread syntax is much more precise and much shorter.
Adding New Property
You can add more properties while cloning the data.
const employee2 = {...employee, salary:12345};
Update Property
You can update specific properties while cloning the data.
const employee2 = {...employee, Name:’Miller’};
console.log(employee.Name) -- >o/p : David
console.log(employee2.Name) -- >o/p : Miller
NOTE: If two properties have the same name, it will consider the last object property.
Array Types
Cloning
var firstArray=[1,2,3]
var second=[...firstArray]
console.log(second);
Concatenating arrays
const arr1 = [1,2,3];
const arr2 = [4,5,6];// The old way:
const arr3 = arr1.concat(arr2);// With spread syntax this becomes:
const arr4 = [...arr1, ...arr2];
Rest
The rest parameter is used with destructuring syntax to consolidate the remaining properties in a new object you’re working with.
const user = {
'name': 'Alex',
'address': '15th Park Avenue',
'age': 43
}
const {age, ...rest} = user;
console.log(age, rest);
The rest object will have ‘Name and address’ properties only.
Addition JavaScript Shorthand Hacks:
Converting a String into a Number
you can convert strings to numbers using a unary plus operator
var x = '23';console.log(parseInt(x));
console.log(Number(x));
console.log(+x);
Null, Undefined, Empty checks
// Longhand version
if(productName !== undefined || productName !== "" || productName !== null){
console.log(productName)
}// Shorthand version
if(productName){
console.log(productName)
}
Template Literals
A lot of developers still use the + character to concatenate strings variables. Again thanks to ES6, we can now make it much lighter with the ${} and `:
// longhand
const winnerMsg = 'Congrats to the winner: ' + winnerName + ', you got a ' + gift;// shorthand
const winnerMsg = `Congrats to the winner: ${winnerName}, you got a ${gift}`;
Multi-line String
// Longhand
const msg = 'Working in conjunction with humanitarian aid agencies,\n\t'
+ 'we have supported programmes to help alleviate human suffering. \n\t';//Shorthand
const msg = `Working in conjunction with humanitarian aid agencies,
we have supported programmes to help alleviate human suffering.`;