JavaScript tips and tricks
Here are some tips and tricks to expand your knowledge about the JavaScript language. Some are well known while others will blow your mind.
Remove all duplicates from an array
const numbers = [1, 33, 8585, 33, 1, 2, 56, 1];
const uniqueNumbers = [...new Set(numbers)];
// [1, 33, 8585, 2, 56]
I find this trick to be very elegant and short. We create a new Set, a Set can only store unique values so if we try to add a value that already exists it will just ignore them. After that we spread the Set into a new array.
Simplify multi condition check
const color = "green";
if(color === "orange" || color === "green"
|| color === "blue" || color === "white") {
console.log("nice color");
}
I'm sure you have seen code like this before, not the prettiest to look at. Here is a more elegant solution.
const color = "green";
const prettyColors = new Set(["orange", "green", "blue", "white"]);
if(prettyColors.has(color)) {
console.log("nice color");
}
With the help of a Set, we can use the has method, if the specified value exists in the Set it will return true. By also putting the Set in a variable we can read the if statement as plain English.
Simulate named parameters
const startGame = (players, game, difficulty, maxTime, tries) => {
// Do something
}
startGame(["Tomas32", "Alice2"], "Connect Four", "easy", 30, 5);
The problem with this is we have no idea what the different arguments are used for, the only way to know it, is we have to go to the startGame function and try to figure it out there. Another problem is we have to give all the arguments in the right order.
Languages like Python have named parameters, in JavaScript we don't have that but we can simulate it.
const startGame = ({players, game = "Blackjack",
difficulty = "easy", maxTime, tries} = {}) => {
// Do something
}
startGame({
tries: 5,
maxTime: 30,
game: "Connect Four",
players:["Tomas32", "Alice2"]
}
);
We can immediately see what the different arguments do and we can pass them in any order. Another benefit is we can set default values for any key. In this case, we set it for game and difficulty, notice we never pass difficulty so it will be set to "easy".
We can set default parameters in the first example but if we wanna set it for game we also have to set a default value for all parameters that comes after.
Iterating over an object
const car = {
name: "Volvo",
model: "s70",
weight: "1400Kg",
color: "blue"
};
Object.entries(car).forEach(([key, val]) => {
console.log(`${key} - ${val}`);
});
Object.entries returns an array of key-value pairs. After that, we use some destructuring to get the key and the value, we can now iterate over the object in a neat way.
Object property shorthand
const rooms = 3;
const oceanView = true;
const color: "yellow";
const house = {
rooms: rooms,
oceanView: oceanView,
color: color
};
Imagine you have a couple of variables and you want to store them in an object, this is the old way of doing that but can we can do it in a shorter way.
const rooms = 3;
const oceanView = true;
const color: "yellow";
const house = {
rooms
oceanView
color
};
With this syntax we don't have to specify keys in our object, all keys will be set to the name of the variable.
some() and every()
I feel that some() and every() methods for arrays are sometimes forgotten, they are great methods that abstract a lot of logic away.
Some()
Search an array and check if one of the elements satisfy the condition. if a match is found it will stop the iteration for remaining values and return true. If no match is found it will return false.
const cars = [
{
name: "Volvo",
model: "S70",
},
{
name: "BMW",
model: "530e",
},
{
name: "Mercedes Benz",
model: "A-Class",
},
]
cars.some(car => car.name === "Volvo"); // true
In this case it will return true because a Volvo car exist in the array.
every()
Search an array and check if all elements satisfy the condition. If it does return true else return false.
const cars = [
{
name: "Volvo",
model: "S70",
},
{
name: "Volvo",
model: "XC90",
},
{
name: "Mercedes Benz",
model: "A-Class",
},
]
cars.every(car => car.name === "Volvo"); // false
This will return false because not every car in the array is Volvo.
Swap variables
Maybe the first way you think of might be to use a temp variable like this.
let a = 13;
let b = 10;
let temp = a;
a = b;
b = temp;
While this works there is an alternative way to do it.
let a = 13;
let b = 10;
let [a, b] = [b, a];
This looks very clean and elegant , here we create a new array with our variables and use destructuring assignment.
Fill an array with random values
Array.from({length: 100}, () => Math.floor(Math.random() * 10) + 1);
Array.from creates a new array instance. We specify length property to be 100, pass a function to generate a random value between 1 and 10.
Conclusion
In this article we have looked at some neat tricks for JavaScript, I hope you learned something new. What are your favorite tips and tricks?