My Top 10 Favorite JavaScript Tips and Tricks

Emma Delaney
6 min readJul 25, 2023

JavaScript is a web programming language developed and used for creating interactive web pages. Interactive is a fancy word that can be reduced to the interaction between the user and the webpage.This interaction is based on the functionality of web pages and not manual intervention.

Thanks to the many JavaScript frameworks that have been released in recent years, it has clearly become the go-to choice for web application development. Here are some of the most popular JavaScript frameworks:

1. Time the execution of your code

console.time('Execution Time');

await functionToBeMeasured();

console.timeEnd('Execution Time');

The time method is an invaluable tool for developers who want to deliver high-performance code. It takes a timer name as a parameter and expects to receive a call to timeEnd in which the same timer name is provided.

The timeEnd method returns the elapsed time in milliseconds between two function calls, allowing programmers to quickly identify bottlenecks in their code and easily refactor them.

This approach is much better than manually calculating elapsed execution time because it is built-in and widely supported by modern browsers.

Must Read : The Salary Of A JavaScript Developer

2. Casting values in arrays using map

const numbers = ["65", "12", "4", "-0.23", "6.543"];
const newArr = numbers.map(Number)
console.log(newArr) //Array(5)[ 65,12,4,-0.23,6.543 ]

This is probably one of the simplest tricks in this article, but it provides a very elegant solution for converting an array of numeric values ​​represented as strings to JavaScript numbers (all JavaScript numbers are 64-bit floating point).

map method of Array and passing Number as a parameter for each array value, calls the constructor of Number and this return result.

3. Wait until multiple promises are complete

const promises = [
Promise.resolve(100),
fetch("http://localhost/"),
fetch("http://localhost/api/v1l/books"),
];

const statusPromises = await Promise.all(promises);
console.log(statusPromises); // ©: 100, 1: Request response, 2: Request response
console.log("Promises finished execution");

This trick is handy when you need to run multiple tasks and wait for them to complete. Since each task is executed asynchronously, they can be processed in parallel, and the returned data can be used after all promises have been resolved.

Remember that if a single promise is rejected, Promise.all will also immediately return a rejected promise.

You can use this trick if you are developing a microservices architecture and need large non-sequential data as quickly as possible from multiple points ending in.

O Once all the promises are resolved, Promise.all returns a promise that resolves to an array of the results of the originally provided promises.

As with any promise, you can also specify a callback to process the results.

4. Remove duplicates from arrays using Set

const numbers = [1, 2, 3, 4, 4, 4, 4, 5, 6, 6, 7];
const fruits = ["apple”, "pear", "banana", “apple”, "apple", “cherry"];

const uniqueNumbers ..new Set(numbers)];
const uniqueFruits = [...new Set(fruits)];

console. log(uniqueNumbers); // [ 1, 2, 3, 4, 5, 6, 7 ]
console. log(uniqueFruits); // ["apple”, "pear", “banana”, "cherry"

A simple but very effective way to remove duplicate arrays with a single line.

In this example, we also used the spread operator shown recently to expand the array and create an array.

This trick works great with values ​​of all kinds and even fixes some of JavaScript’s weird equality behavior.

You can also use arrays to remove duplicate arrays of complex objects.

5. Use the spread operator to shallow copy objects (and arrays!)

const numbers = [1, 2, 3, 4, 5, 6, 7, 8];
const person = {
name: "Lewis",
active: false,
}

console. log([...numbers, 9, 10]); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
console.log({ ...person, active: true }); // { name: "Lewis", active: true }
console.log({ ...person, age: 25 }); // { name: "Lewis", active: false, age: 25 }

With the introduction of extended syntax in JavaScript, it is now easier than ever to extend objects or arrays and make copies.

This is especially useful when you need to manage state in React or React Native, as all you have to do is copy the current state with the object literal, change selected properties, and change state with the state binding provided by useState.

This is also a great way to concatenate arrays or merge objects with a single line instead of having to iterate over each instance and manually merge them.

6. Function default params

let greetings = (name, message='Hello,') => {
return `${message} ${name}`;
}

console.log(greetings('Jack'));
console.log(greetings('Jack', 'Hola!'));

In JavaScript, function arguments (or parameters) are like variables local to that function. You may or may not pass values ​​to it when calling the function. If you don’t pass a value for a parameter, the parameter becomes undefined and can lead to unwanted side effects.

There is an easy way to pass a default value when setting function parameters. Here is an example where we pass the default value Hello to the message parameter of the Greetings function.

7. Leverage the destructuring assignment syntax

const company = {
employees: 10,
founder: "John Doe",
products: ["Phones”, "Hardware", “Laptops"],
};


const { employees, founder } = company;
const { @: phones, 2: laptops } = company.products;

console.log(employees); // 10
console.log(founder); // John Doe
console.log(phones); // Phones
console.log(laptops); // Laptops

Another quick and easy trick you can use to extract the information most relevant to you from a JavaScript object.

The Destruct syntax allows developers to quickly unpack values ​​from arrays or object properties into named variables.

This syntax allows for several tricks, e.g. For example, swapping single-line variables or parsing only the meaning of properties of a returned object.

8. The default value with OR

If you ever want to set a default value for a variable, you can easily do so with the OR(||) operator.

let person = {name: 'Emma'};
let age = person.age || 35; // sets the value 35 if age is undefined
console.log(`Age of ${person.name} is ${age}`);

But wait, he has a problem. What if the person is 0 years old (maybe a newborn)? Age is calculated as 35 (0 || 35 = 35). This is unexpected behavior.

Enter the nullish coalescing operator (??).It is a logical operator that returns its right operand if its left operand is nullor undefined, and returns its left operand otherwise.

To complete the above code with the ??rewrite operator,

let person = {name: 'Jack'};
let age = person.age ?? 35; // sets the value 0 if age 0, 35 in case of undefined and null
console.log(`Age of ${person.name} is ${age}`);

9. Format JSON output with spaces

A simple but very efficient tool to export readable JSON by specifying in the third parameter the number of spaces to use for indentation.

The second parameter is replacement and can be a function that controls the string building process or it can be an array. In this case, it specifies the name of the properties to include in the string output.

const profile = {
name: "Emma",
age: 23,
dateJoined: "11-01-2019",
};

JSON.stringify(profile, null, 2);

//{

// "name": "Emma",

// Tage": 23,

// “"dateJoined": "11-01-2019"
//}

10. isInteger

let mynum = 123;
let mynumStr = "123";

console.log(`${mynum} is a number?`, Number.isInteger(mynum));
console.log(`${mynumStr} is a number?`, Number.isInteger(mynumStr));
//123 is a number?
//true
//123 is a number?
//false

There is a much easier way to determine if a value is an integer. The JavaScript Numbers API provides a method called isInteger() for this purpose. It is very useful and it is better to be aware of it.

Interested in more tech articles ?

Stay tuned, I’ll be posting more articles on JavaScript and web development in the coming weeks.

You can also check out my other articles if you’re interested in what I write.

Must try my new extension and make your browser beautiful: Install Now

--

--