JavaScript Tips & Tricks

Best JavaScript tricks and tips

By Gennaro Nucaro

  • JavaScript

Conditionally Add Properties to an Object

We can use the spread operator ... to dynamically add properties to an object.

1const condition = true;
2
3const player = {
4  id: 1,
5  name: 'Super Mario',
6  ...(condition && { age: 25 }),
7};
8console.log(player); // { id: 1, name: 'Super Mario', age: 25 }

The && operator in JavaScript returns the second operand only if the first is evaluated as true. So, if condition is true, the player object will be given the property { age: 25 }. If condition had been false, nothing would have been added.

Check if a Property Exists in an Object

We can use the in keyword to check if a property exists in an object.

1const jobAdvertisement = { company: 'google', workLocation: 'Milan' };
2console.log('workLocation' in jobAdvertisement); // returns true
3console.log('salary' in jobAdvertisement); // returns false

Clone Objects and Arrays

In JavaScript, cloning can be done in two ways: shallow copy and deep copy.

Shallow copy only copies the top level properties. If the original contains references to nested objects or arrays, the copy will have references to the same elements, not independent copies.

Deep copy creates a complete copy, copying all levels of properties. This means every reference to a nested object or array is recursively copied, resulting in a completely independent copy.

Shallow Copy

1const person = {
2  name: "Walter",
3  job: "teacher",
4};
5
6// new object
7const newPerson = { ...person }; // {name: 'Walter', job: 'teacher'}
8
9// we can also modify or add properties
10const newPersonTwo = { ...person, job: "cook" };
11// {name: 'Walter', job: 'cook'}
12const newPersonThree = { ...person, age: 50 };
13// {name: 'Walter', job: 'teacher', age: 50}
14
15const numbers = [1, 2, 3, 4, 5, 6, 7];
16const newNumbers = [...numbers]; // [1, 2, 3, 4, 5, 6, 7];

In the above example, we use the spread operator ... to create a shallow copy of the person object and the numbers array. Any modifications to the original or the copy will not affect the other.

Deep Copy

1const person = {
2  name: "Walter",
3  job: "teacher",
4  address: {
5    country: "New Mexico",
6    city: "Albuquerque",
7  },
8};
9
10// method 1
11const clonedPerson = JSON.parse(JSON.stringify(person));
12// method 2
13const clonedPersonTwo = structuredClone(person);
14
15const arrayWithObjects = [
16  { id: 1, value: 'a' },
17  { id: 2, value: 'b' },
18  { id: 3, value: 'c' },
19];
20
21const clonedArray = JSON.parse(JSON.stringify(arrayWithObjects));
22const clonedArrayTwo = structuredClone(arrayWithObjects);

In the above example, we use JSON.parse(JSON.stringify(person)) to create a deep copy of the person object. Alternatively, we can use structuredClone, which is a more modern and direct method for deeply cloning objects. In both cases, every level of the object is copied, producing a completely independent copy.

Merge Arrays and Objects

In JavaScript, we can use the spread operator ... to merge objects and arrays in a simple and readable way.

1const person = {
2  name: "Walter",
3  job: "teacher",
4};
5
6const address = {
7  state: "New Mexico",
8  city: "Albuquerque",
9};
10
11// Merge two objects
12const personAddress = { ...person, ...address };
13console.log(personAddress);
14// Output: {name: 'Walter', job: 'teacher', state: 'New Mexico', city: 'Albuquerque'}
15
16const numbers = [1, 2, 3, 4, 5, 6, 7];
17const someNumber = [8, 9, 10];
18
19// Merge two arrays
20const newArrayNumbers = [...numbers, ...someNumber];
21console.log(newArrayNumbers);
22// Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

Use Destructuring to Extract Values from Objects

Destructuring in JavaScript allows you to extract values from objects in a simple and readable way.

1const player = {
2  name: "Mario",
3  age: 25,
4  occupation: "plumber"
5};
6
7// Extract values using destructuring
8const { name, age, occupation } = player;
9console.log(name); // Mario
10console.log(age); // 25
11console.log(occupation); // plumber
12
13// You can also set default values
14const { name, age, occupation, lastname = "Super", isBig = true } = player;
15console.log(lastname); // Super
16console.log(isBig); // true

Use Destructuring to Extract Values from Arrays

Destructuring can also be used to extract values from arrays in a similar way.

1const players = ["Mario", "Luigi"];
2
3// Extract values using destructuring
4const [firstPlayer, secondPlayer] = players;
5console.log(firstPlayer); // Mario
6console.log(secondPlayer); // Luigi
7
8// You can also set default values
9const [firstPlayer, secondPlayer, thirdPlayer = "Peach"] = players;
10console.log(firstPlayer); // Mario
11console.log(secondPlayer); // Luigi
12console.log(thirdPlayer); // Peach

Set Dynamic Property Names for Objects

In JavaScript, you can dynamically assign names to object properties using square brackets [].

1const dynamic = 'age';
2
3const person = {
4  name: 'Jack',
5  [dynamic]: 38
6};
7console.log(person); // { name: 'Jack', age: 38 }

We can use the same trick to retrieve the value of a property using a dynamic key:

1const keyName = 'age';
2console.log(person[keyName]); // returns 38

Pass Objects as Arguments

You can pass objects as arguments to functions to improve code readability and make parameters clearer.

1const createPlayer = ({ name, age, job }) => {
2  // some logic
3  console.log(`Name: ${name}, Age: ${age}, Job: ${job}`);
4}
5
6createPlayer({
7  name: 'Mario',
8  job: 'plumber',
9  age: 25,
10});

How to Iterate Over Objects

1const person = { name: 'Jack', age: 38, job: 'doctor' };
2
3// Using for...of and Object.entries
4for (const [key, value] of Object.entries(person)) {
5  console.log(`Key: ${key}, Value: ${value}`);
6}
7
8// Using Object.keys and forEach
9Object.keys(person).forEach(key => {
10  const value = person[key];
11  console.log(`Key: ${key}, Value: ${value}`);
12});
13
14// Using Object.entries and forEach
15Object.entries(person).forEach(([key, value]) => {
16  console.log(`Key: ${key}, Value: ${value}`);
17});
18
19// Output of the three methods
20// Key: name, Value: Jack
21// Key: age, Value: 38
22// Key: job, Value: doctor

Sort an Array Alphabetically

1const array = ["Banana", "apple", "Cherry", "date"];
2array.sort((a, b) => a.localeCompare(b));
3console.log(array);  // ["apple", "Banana", "Cherry", "date"]

Using Boolean to Check if a Value is True

1const array = [null, 'Apple', undefined, false, true, 0];
2
3// Filter out falsy values
4const filtered = array.filter(Boolean);
5console.log(filtered); // returns ['Apple', true]
6
7// Check if at least one value is truthy
8const someTrue = array.some(Boolean);
9console.log(someTrue); // returns true
10
11// Check if all values are truthy
12const everyTrue = array.every(Boolean);
13console.log(everyTrue); // returns false

Using map and Number for Quick Casting

1const numbers = ["0", "123", "3.14", "-256", "6323.1431"];
2const newNumbers = numbers.map(Number);
3console.log(newNumbers); // [0, 123, 3.14, -256, 6323.1431];

Removing Duplicates from an Array with Set

We can use Set to remove duplicates from an array. A Set object in JavaScript allows you to store unique values of any type.

1const numbers = [0, 0, 1, 2, 2, 3, 3, 4, 5, 6, 7, 7, 8, 8, 9];
2const players = ["Mario", "Mario", "Luigi", "Luigi", "Toad"];
3
4const uniqueNumbers = [...new Set(numbers)];
5const uniquePlayers = [...new Set(players)];
6
7console.log(uniqueNumbers); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
8console.log(uniquePlayers); // ["Mario", "Luigi", "Toad"]

By converting an array into a Set, duplicates are automatically removed. Using the spread operator [...new Set(array)], we can convert the Set back into an array with only unique values.

Using the Nullish Coalescing Operator ??

The Nullish Coalescing Operator ?? in JavaScript is used to provide a default value when the left-hand operand is null or undefined.

1const userName = null ?? "Default User";
2console.log(userName); // Output: "Default User"
3// If userName is null, "Default User" is assigned
4
5const userStatus = undefined ?? "Guest";
6console.log(userStatus); // Output: "Guest"
7// If userStatus is undefined, "Guest" is assigned
8
9const userAge = 0 ?? "Age not specified";
10console.log(userAge); // Output: 0
11// If userAge is 0, 0 is retained because 0 is a valid value (not null or undefined)
12
13const userMessage = "" ?? "No message provided";
14console.log(userMessage); // Output: ""
15// If userMessage is an empty string,
16// the empty string is retained because it is a valid value (not null or undefined)

Be careful when using || as you might get unexpected results. The OR operator returns the first "truthy" operand it finds, which means it treats values like 0, "", false as "falsy" and replaces them with the provided default value.

1const number = 0 || "new number";
2console.log(number); // Output: "new number"
3// 0 is considered "falsy", so it is replaced with "new number"
4
5const string = "" || "new string";
6console.log(string); // Output: "new string"
7// "" is considered "falsy", so it is replaced with "new string"

Using Optional Chaining ?.

The Optional Chaining Operator ?. allows you to safely access properties and methods of objects that might be null or undefined without throwing errors, making the code cleaner and more readable.

1const user = {
2  name: "Alice",
3  address: {
4    city: "Wonderland",
5    zip: "12345"
6  },
7  greet: function() {
8    return "Hello!";
9  }
10};
11
12const cityName = user?.address?.city;
13console.log(cityName); // Output: "Wonderland"
14
15const countryName = user?.address?.country;
16console.log(countryName); // Output: undefined
17
18const greeting = user?.greet?.();
19console.log(greeting); // Output: "Hello!"
20
21const farewell = user?.farewell?.();
22console.log(farewell); // Output: undefined
23
24const users = [
25  { name: "Charlie" },
26  null,
27  { name: "Hurley" }
28];
29
30const firstUserName = users[0]?.name;
31console.log(firstUserName); // Output: "Charlie"
32
33const secondUserName = users[1]?.name;
34console.log(secondUserName); // Output: undefined
35
36// Example: Using in combination with Nullish Coalescing Operator
37const settings = {
38  preferences: {
39    theme: null
40  }
41};
42
43const userTheme = settings?.preferences?.theme ?? "default theme";
44console.log(userTheme); // Output: "default theme"

Casting to Boolean with !!

The double negation operator !! is used to convert any value to a boolean in JavaScript. It is a quick and concise method for casting to boolean.

Falsy Values

1const value1 = null;
2const value2 = undefined;
3const value3 = 0;
4const value4 = "";
5
6console.log(!!value1); // Output: false
7console.log(!!value2); // Output: false
8console.log(!!value3); // Output: false
9console.log(!!value4); // Output: false

Values such as null, undefined, 0, and empty strings "" are considered falsy in JavaScript, and thus are converted to false when applied with !!.

Truthy Values

1const value1 = 1;
2const value2 = "Hello";
3const value3 = [];
4const value4 = {};
5
6console.log(!!value1); // Output: true
7console.log(!!value2); // Output: true
8console.log(!!value3); // Output: true
9console.log(!!value4); // Output: true

Values such as non-zero numbers, non-empty strings, arrays, and objects are considered truthy in JavaScript, and thus are converted to true when applied with !!.

Ternary Operator

The ternary operator is a concise way to write an if-else statement.

1const age = 20;
2const canVote = age >= 18 ? "Yes" : "No";
3
4console.log(canVote); // Yes

Using the Rest Parameter

1function sum(...numbers) {
2  return numbers.reduce((accumulator, current) => accumulator + current, 0);
3}
4
5console.log(sum(1, 2, 3));  // 6
6console.log(sum(4, 5, 6, 7));  // 22
7console.log(sum(10));  // 10
8
9function greet(first, ...rest) {
10  console.log(`Greet ${first}!`);
11  console.log('Greetings also to:', rest.join(', '));
12}
13
14greet('Antonio', 'Bob', 'Charlie', 'Dave');
15// Output:
16// Greet Antonio!
17// Greetings also to: Bob, Charlie, Dave

Measure Performance with console.time

1console.time("test")
2
3let value = 1;
4for (let i = 0; i < 100_000_000; i++) {
5  value += i;
6}
7
8console.timeEnd("test")

Printing with console.table

1const players = ["Mario", "Luigi", "Toad"];
2
3const player = {
4  name: "Mario",
5  age : 25
6}
7console.table(player);
8console.table(players);
console.log arrayconsole.log object

Styling the console.log

1const styles = `padding: 50px;
2background-color: blue;
3color: white;
4font-size:50px;
5`;
6
7console.log("%c Ciaoooooo !!!", styles);
console.log