5 Must-know Javascript Tips & Tricks

Rizwan Ali
2 min readJul 13, 2020

Do you know them all?

JavaScript keeps adding new and neat features. Sometimes, it’s hard to keep up. In this article, I’ll share a couple of cool tips & tricks to keep you up to speed and deepen your JS knowledge.

Imagine having an array with some duplicate items and wanting to filter out only the unique ones.

You could try writing a map or filter to achieve this. Alternatively, ES6 introduces the Set object, which solves this problem in just 1 line of code.

const arrayWithUniqueItems = [...new Set([1, 2, 3, 3,])]
// [1, 2, 3]

Now, this example uses integers, but you can use strings and floating-point numbers as well!

For alittle more in-depth knowledge about the Set object, check out this article by Claire-Parker Jones.

Now this is a tricky one.

Shortening your “if” statements can be a great way to simplify your code.

However, if you need to write more complicated statements, you should definitely go for the first option.

// Instead of using this // You can use this// Or this
if (iAmHungry) {
if (iAmHungry) bakeAnEgg()
iAmHungry? bakeAnEgg() : 0
bakeAnEgg()
}

Remember, readability & ease-of-use are more important than a couple less lines of code.

A great way of shortening an array is by redefining its length property.

let array = [0, 1, 2, 3, 4, 5, 6, 6, 8, 9]
array.length = 4 // Result: [0, 1, 2, 3]

Important to know though is that this is a destructive way of changing the array. This means you lose all the other values that used to be in the array.

Let’s say you want to combine multiple objects into one object containing them all.

The spread operator ( … ) is a great way to achieve this!

const obj1 = {'a': 1, 'b': 2}// Combine them using the spread operator
const obj2 = {'c': 3}
const objCombined = {...obj1, ...obj2, ...obj3}
const obj3 = {'d': 4} // Result: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

Something to keep in mind while using this is that whenever you update one of the objects, it doesn’t reflect those changes in the combined object.

JavaScript can access the current URL using the window.location object. Pretty neat, but even cooler is that this object contains certain parts of the URL as well.

Get access to the protocol/host/pathname/search/and more!

// JavaScript can access the current URL in parts. For this URL:window.location.protocol == `https:`
`
window.location.host == `thatsanegg.com`
window.location.pathname == `/example/index.html`
window.location.search == `?s=article` https://thatsanegg.com/example/index.html?s=article`

Originally published at https://blog.prototypr.io on July 13, 2020.

--

--