Dan D Kim

Let's share stories

Here is a really useful Javascript operator that you can use in coding interviews

2020-01-20 Dan D. Kimjavascript

For those of you planning to use Javascript in your coding interviews, this operator will come in very handy if you don’t know it already.

Spread Operator

The spread operator has been introduced in ES6 and here’s how it can help you.

Let’s say you have to manipulate arrays.

This is the old-fashion way of doing it.

// ES5

// Cloning an array
const array = ['a', 'b', 'c']
const arrayCopy = array.slice()

// Concatenating arrays
const firstArray = ['a', 'b', 'c']
const secondArray = ['d', 'e', 'f']
const concatArray = firstArray.concat(secondArray)

With the spread operator, the code above looks like this.

// ES6

// Cloning an array.
const array = ['a', 'b', 'c']
const arrayCopy = [...array]

//Concatenating arrays
const firstArray = ['a', 'b', 'c']
const secondArray = ['d', 'e', 'f']
const concatArray = [...firstArray, ...secondArray]

What’s even better is that unlike concat, you can use the spread operator to concatenate your secondArray at a particular index.

const array = ['b', 'c', 'd']
const concatArray = ['a', ...array, 'e', 'f']

And then of course, we can use spread operators for copying objects as well, which is always nice.

Here’s the ES5 way of copying an object.

const dan = {
  name: 'Dan',
  occupation: 'Programmer'
}
// ES5
const danCopy = Object.assign({}, dan)
// ES6
const danCopy = { ...dan }

Essentially, the spread operator is destructuring the object and is assign individual properties to the new object. This is what it is doing in { ...dan }.

Why are these useful for coding interviews?

Typically in coding interviews, you code on a whiteboard. Even at Google, only a select number of offices offer laptops as a coding medium. This was my case when interviewing at Google Montreal.

You will have limited time when solving a question, and having to write less code will ultimately be to your benefit, because you will have more time to debug and discuss other follow-up questions.

The spread operator saves me time and whiteboard space. About whiteboard space, it’s funny. You may not realize how quickly you run out of space on the whiteboard unless you practice on it!!

Hope you learned something.

Happy programming :)