Cool JavaScript tips to make your code shorter and cleaner

Kinanee Samson - Mar 25 '21 - - Dev Community

Destructuring

Destructuring is a fancy word that is used to describe the process of unpacking values from an array or extracting properties from objects and storing them inside variables.
From the above description, we have;

  • array destructuring
  • Object destructuring.

Before i knew about destructuring i used to extract valued from arrays like this.

const heroes = ['batman', 'superman', 'cyborg']

const batman = heroes[0]
const superman =  heroes[1]
const cyborg = heroes[2]

console.log(batman, superman, cyborg)
// batman, superman, cyborg
Enter fullscreen mode Exit fullscreen mode

And i used to extract object properties like this

const superman = { 
name: 'superman',
alias: 'clark kent',
powers: ['super speed', 'super strength', 'heat vision']
}

const name = superman.name
const alias = superman.alias
const powers = superman.powers

console.log(name, alias, powers)
// superman, clark kent, ['super speed', 'super strength', 'heat vision']
Enter fullscreen mode Exit fullscreen mode

This was okay but it felt repetitive and a lil bit stressful having to repeat the array or object name. Then i knew about destructuring, i now obtain values from an array like this;

const heroes = ['batman', 'superman', 'cyborg']
const [ batman, superman, cyborg ] = heroes

console.log(batman, superman, cyborg)
// batman, superman, cyborg
Enter fullscreen mode Exit fullscreen mode

And i extract object properties like this

const superman = { 
name: 'superman',
alias: 'clark kent',
powers: ['super speed', 'super strength', 'heat vision']
}
const { name, alias, powers } = superman

console.log(name, alias, powers)
// superman, clark kent, ['super speed', 'super strength', 'heat vision']
Enter fullscreen mode Exit fullscreen mode

This method is shorter, cleaner and easier to read.
We could also use it for functions too, especially when the function accepts a lot of parameters.
I used to write those type of functions like this;

function createHero (name, alias, universe, colors, swornEnemy, favoriteTool) {
return { name, alias, universe, colors, swornEnemy, favoriteTool }
}
Enter fullscreen mode Exit fullscreen mode

Now i just pass in an array or object and destructure just what i need to create my hero.

// using array destructuring
function createHero (properties) {
// i want to create a hero with only a name and an alias
const [name, alias] = properties
return { name, alias }
// we could still extract more properties if we wanted
}

const superHero = createHero([ 'superman', 'clark kent', ['heat vision', 'super speed'] ])

console.log(superHero)
// {name: 'superman', alias: 'clark kent'}
Enter fullscreen mode Exit fullscreen mode

We could still use object destructuring and our function will look like this.

// using object destructuring
function createHero (properties) {
// i want to create a hero with only a name and an alias
const {name, alias } = properties
return { name, alias }

const superHero = createHero({name: 'superman', alias: 'clark kent', powers: ['heat vision', 'super speed'] })

console.log(superHero)
// {name: 'superman', alias: 'clark kent'}
Enter fullscreen mode Exit fullscreen mode

we can also destructure when we pass in the parameter

function createHero ({name, alias}) {
// i want to create a hero with only a name and an alias 
return { name, alias }
}

const superHero = createHero({name: 'superman', alias: 'clark kent', powers: ['heat vision', 'super speed'] })

console.log(superHero)
// {name: 'superman', alias: 'clark kent'}
Enter fullscreen mode Exit fullscreen mode

To read more articles like this please visit Netcreed

Object Property-Value shorthand

There is a shorthand method for declaring properties on objects, you don't explicitly need to declare the property value on the object itself, you can declare a variable that holds the value for the property and only enter the variable name on the object amd JavaScript takes care of the rest.
So i used to declare those type of properties like this

const superman =  {
name: 'superman',
alias: 'clark kent'
}

console.log(superman)
// {name: 'superman', alias: 'clark kent' }
Enter fullscreen mode Exit fullscreen mode

Now i just do this;

const name = 'superman'
const alias = 'Clark Kent'

const superman = { name, alias }

console.log(superman)
// { name: 'superman', alias: 'clark kent' }
Enter fullscreen mode Exit fullscreen mode

Template Strings

This is another cool feature i use, rather than concatenate variables and strings, you can use template strings(back ticks) and output a variable or the result of an expression directly inside the string.
When i still used concatenation

//without template literals
const hero = 'superman'

console.log('my favorite hero is '+hero)
Enter fullscreen mode Exit fullscreen mode

When i moved to template strings

//with template literals
const hero = 'superman'

console.log(`my favorite hero is ${hero}`)
// my favorite hero is superman
Enter fullscreen mode Exit fullscreen mode

We use ${} to output variable names and write expressions inside template strings, the variable name or expresssion inside the curly braces.

//with template literals
const hero = 'superman'

console.log(`my favorite hero is ${hero === 'superman' ? hero: 'superman'}`)
// my favorite hero is superman
Enter fullscreen mode Exit fullscreen mode

Spread Operator

The spread operator allows us to expand a list of items into a function that accepts an array, multiple parameters or an iterable. A spread operator can convert an array into a list of items or dump a list of items into functions or arrays or even objects. The spread operator is jus three dots followed by the name of the it er able (...iterable)

// converting and array to a list of items using the spread operator

const heroes = [' hulk', 'spiderman', 'thor']

const marvelHeroes = [...heroes]

console.log(marvelHeroes)
// [' hulk', 'spiderman', 'thor']
Enter fullscreen mode Exit fullscreen mode

We can use the spread operator for functions that accept multiple values like console.log() or array.push.

const marvelHeroes = [' hulk', 'spiderman', 'thor']
const dcHeroes = ['superman', 'wonder woman', 'cyborg']

// array.push
heroes.push(...marvelHeroes)
// OR
const heroes = [...dcHeroes]


console.log(heroes)
// [' hulk', 'spiderman', 'thor', 'superman', 'wonder woman', 'cyborg']
Enter fullscreen mode Exit fullscreen mode

We can define a custom function to understand how this works.

function logHeroes (...heroes) {
console.log(...heroes)
}

logHeroes('batman', 'spiderman')
// batman, spiderman
Enter fullscreen mode Exit fullscreen mode

The cool thing about this is any numbet of argument we supply when we call the function is legit, we can call logHeroes and supply only one hero or 6 heroes and the function would log the heroes we supplied.

Spread Operator can also be used to assign properties to objects too. It copies the properties on the object we used it with to the other object we are trying to assign values to much like Object.assign()

const name = 'superman'
const alias = 'clark kent'
const universe = 'DCU'

const hero = {name, alias}

const superman = { universe, ...hero }

console.log(hero)
// {name: 'superman', alias: 'clark kent' }
console.log(superman)
// {name: 'superman', alias: 'clark kent' , universe: 'DCU' }
Enter fullscreen mode Exit fullscreen mode

There are more cool features of javascript we did not cover in this article, maybe we will go over those in another one.
I hope you find this article useful.

To read more articles like this please visit Netcreed

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .