JavaScript Pro Tips - Code This, NOT That

Debug better with better use of console.log

Ya, console.log is awesome, but what if you have to log more than one object at a time, maybe 2 or 3? That is when computer property names come in handy. Which goes in like this,

console.log({foo, bar, baz})

Where foo, bar, and baz are your objects.

you can also make it stand out using some custom CSS

console.log('%C My Friends', 'color:orange')
console.log({foo, bar, baz})

You might also just use the table function like

console.log([foo, bar, baz]) //as long as the objects share the same property.

For performance profiling console.time becomes very handy.

Making your code concise and efficient with restructuring

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

const turtle = {
    name: 'bob',
    meal: 10,
    legs: 4,
    diet: 'berrie'

function feed({name, meal, diet}){//instead of passing the whole animal object and using its property 
    return `Feed ${name} ${meal} killos of ${diet}`;

More readable and less annoying with template literals

A code with a number of concatenations, computations etc was common in JS. Now thanks to template literals this messiness is no longer necessary. Template literals allow embedded expressions so instead of concatenating we can interpolate them within strings like:-

`${name} string text ${expression} string text`

Spread syntax (...)

Spread syntax is used to make our code much more readable and easier to write and understand. For example, instead of pushing an element to an array every time we want to add one, we can use Spread syntax like this.

let animal = ['cat', 'dog']
animal = [...animal, 'fish', 'turtle']//This will save us from repeatedly writing an animal.push
animal = ['fish', 'turtle', ...animal]//This works similary but instead of push, it does shift.

Awesome loops

Instead of rushing into for loops every time, consider array map, filter, and reduce; which are all higher-order functions.


Async-wait is a new way to write asynchronous code.

Subscribe for coding videos

Keep growing professionally with just three curated videos weekly.

We hate spam as much as you do.