DEV Community

sanderdebr
sanderdebr

Posted on

5 Simple but Useful Javascript Tricks

JavaScript is currently the most popular language used on Github, according to www.githut.info. In this article I will show you 8 simple but useful tricks which you can use to improve your JavaScript on day to day basis.


1. Object Destructuring

Destructuring in JavaScript allows you to extract data from objects, arrays maps and sets into their own variables. Basically it is a shortcut for assigning variables from objects properties. Let's say you want to extract data from an object which is called myCar that contains nested objects and arrays.

Without destructuring:

const myCar = {
   name: 'ferrari',
   speed: 10,
   usedBy: ['Mike', {company: 'Microsoft'}],
   parkedAt: {
      street: 'Mulholland Dr'
   }
}

const name = myCar.name;
const speed = myCar.speed;
const company = myCar.usedBy[1].company;
const street = myCar.parkedAt.street;

And so on...

With object destructuring:

const myCar = {
   name: 'ferrari',
   speed: 10,
   usedBy: ['Mike', {company: 'Microsoft'}],
   parkedAt: {
      street: 'Mulholland Dr'
   }
}

const { name, speed, usedBy, parkedAt: { street }} = myCar;

console.log(name, speed, person, company);

Much better!

We can even do better by also destructuring off the array usedBy as follows:

const { name, speed, usedBy: [person, {company}], parkedAt: { street }} = myCar;

This technique is also often used in frameworks like React to destructure off the props inside the component declaration. This makes the code much cleaner.

For example:

const ProfileTop = ({
  profile: {
    status,
    company,
    location,
    website,
    social,
    user: { name, avatar }
  }
}) => ( ... rest of component

2. Combining objects

Let's say you have two objects.

const obj1 = { name: 'Peter', age: 45 };
const obj2 = { likes: 23 };

It is very easy to combine them into a new object using the spread operator:

const objCombined = {...obj1, ...obj2 };

Combined

The spread operator is basically syntactic sugar over Object.assign().

The following gives you the same result:

const objCombined = Object.assign({}, obj1, obj2);

You can find more on this inside the official Spread proposal in the EcmaScript repo: https://github.com/tc39/proposal-object-rest-spread/blob/master/Spread.md


3. Rest parameter

The rest parameter uses the same syntax as the spread operator, which can be a bit confusing because they are different things.

The rest parameter converts all arguments of a function to an array, so you do not have to explicitly describe each argument.


const myFunction = (...args) => {
   console.log(args); // array of arguments
   console.log(args[0]); // logs 1
}

myFunction(1, 2, 3, 4, 5);

You can use this for example to send some properties to a component in React without explicitly describing them:

const CollectionsPage = ({ collections }) => (
    <div className="collections-page">
        {collections.map(({ id, ...collectionProps}) => (
            <CollectionItem key={id} {...collectionProps} />
        ))}
    </div>
);

4. Conditionally setting a variable

The conditional ternary operator is a difficult word for a shorthand way of writing an if-else method.

if (finished === true) {
   callFunc();
} else {
   return false;
}

// Is the same as
finished === true ? callFunc() : false;

Notice that this operator returns automatically without the return keyword.

If you only want to have an if-statement you can use &&:

finished === true && callFunc();

5. Improve performance with console.time

A way to track how long your function takes to execute if by using console.time() and console.timeEnd():

console.time("Time this");

for (var i = 0; i < 10000; i++) {
  // Your stuff here
}

console.timeEnd("Time this");

Hope you have learned something from this article! I will soon make part 2.

Top comments (0)