Categories
JavaScript Tips

Even More JavaScript Shorthands

Spread the love

With the latest versions of JavaScript, the language has introduced more syntactic sugar. In this article, we’ll look at handy shortcuts that are easy to read from versions of JavaScript new and old. With them, it’ll save us time and make our code easier to read.

In this article, we’ll look at object properties assignment, finding the index of a function, replacing switch statements with objects, merging objects compacting if statements and more.

Object Properties Assignment

We can use the Object.assign method to shallow copy an object from a new object to another.

For example, if we have the following object:

const foo = {
  foo: 1
}

We can clone it as follows:

const copied = Object.assign({}, foo);

Cloning will copy the structure of its own properties and will prevent the modification of the original object.

This means modifying copied won’t modify foo .

It’s a shallow clone so nested objects aren’t cloned.

We can merge 2 objects into one and return it with Object.assign . For example, if we have the following 2 objects:

const foo = {
  foo: 1
}

const bar = {
  bar: 1
}

Then we can merge them into one and return a new object with the merged structure by running:

const merged = Object.assign(foo, bar);

Then we get:

{foo: 1, bar: 1}

which don’t reference the original objects.

IndexOf and findIndex

We can use the indexOf method to find the location of a primitive element in the array. It returns -1 if it’s not found and the first index that the value if found if it exists.

For example, if we have the following array:

const arr = [1, 2, 3, 4, 1];

Then arr.indexOf(1) will get us 0.

For arrays of objects, we can use the findIndex method to do the same thing. For instance, given the following array:

const people = [{
    name: 'Joe',
    age: 10
  },
  {
    name: 'Joe',
    age: 11
  },
  {
    name: 'Mary',
    age: 13
  },
]

We can use the findIndex method as follows:

people.findIndex(p => p.name === 'Joe')

Then we get 0 since the first entry that has 'Joe' in the name property is the first entry.

Object.entries()

With ES2017, we can get all the key-value pairs of an object by using the Object.entries method. It gets its own key-value pairs and not its prototype.

For example, we can write the following code:

const obj = {
  a: 'foo',
  b: 'bar',
  c: 'baz'
};
const arr = Object.entries(obj);

Then we get back:

["a", "foo"]
["b", "bar"]
["c", "baz"]

Then first entry is the key and the second is the value.

Object.values()

We can use the Object.values method to get the values of the object.

For example, if we have:

const obj = {
  a: 'foo',
  b: 'bar',
  c: 'baz'
};
const arr = Object.values(obj);

Then we get back:

["foo", "bar", "baz"]

, which are the values of the object properties.

Getting Characters of a String Literal

We can either use the charAt method or the bracket notation to do this.

For example, we can write:

'foo'.charAt(0);

or:

'foo'[0];

Then both get us 'f' , which is the first character of 'foo' .

Compact Alternative to Switch

We can use an object as a compact alternative to switch statements.

For example, if we have:

const apple = () => console.log('apple');
const orange = () => console.log('orange');
const grape = () => console.log('grape');
const fruit = 'apple';

switch (fruit) {
  case 'apple':
    apple();
    break;
  case 'orange':
    orange();
    break;
  case 'grape':
    grape();
    break;
  default:
    return;
}

We can replace the switch statement with a plain object:

const fruit = 'apple';

const dict = {
  apple() {
    console.log('apple');
  },
  orange() {
    console.log('orange');
  },
  grape() {
    console.log('grape');
  },
}

dict[fruit]();

Replace if’s with indexOf or includes

If we have something like:

const foo = 1;
if (foo == 1 || foo == 5 || foo == 7 || foo == 12) {
  console.log(foo);
}

We can replace with the indexOf method as follows:

const foo = 1;
if ([1, 5, 7, 12].indexOf(foo) !== -1) {
  console.log(foo);
}

-1 means that that value isn’t found in the array. Any other value indicates the index that the value is located at.

Or we can use the includes method:

const foo = 1;
if ([1, 5, 7, 12].includes(foo)) {
  console.log(foo);
}

includes returns a boolean. It’s true if the value is found in the array and false otherwise.

We can get the characters of a string literal with the charAt method or with the bracket notation.

switch statements can be replaced with objects that act as dictionaries.

With newer versions of JavaScript, we can get an object’s values and key-value pairs, with the Object.values method and Object.entries method respectively.

To get the index of the first occurrence of an array element, we can use the indexOf method for primitives and findIndex for objects.

To copy and merge objects, we can use the Object.assign method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *