JavaScript Tips and Tricks Every Developer Should Know

As a Frontend Developer, I always seek cool tips and tricks to make my coding life easier and more enjoyable. Today, I'd like to share some techniques that I've picked up along the way. I'm sure you'll find these tips handy.

1. A few ways to swap variables

One way of swapping variables would be to use a temporary variable:

let age = 'John Doe';
let name = '40';
let temp;

temp = age;
age = name;
name = temp;

console.log(`Hi, I am ${name} and ${age} years old.`) 
// Output: 'Hi, I am John Doe and 40 years old.'

Using array destructuring is a nice and modern way of swapping the variables:

let age = 'John Doe';
let name = '40'; 

[age, name] = [name, age]

console.log(`Hi, I am ${name} and ${age} years old.`) 
// Output: 'Hi, I am John Doe and 40 years old.'

You can also use an array literal and indexing:

let age = 'John Doe';
let name = '40';

name = [age, age = name][0];

console.log(`Hi, I am ${name} and ${age} years old.`) 
// Output: 'Hi, I am John Doe and 40 years old.'

2. Three methods to create a shallow copy of the array.

Using Spread Operator

The spread operator ... allows you to expand elements of an iterable. You can use it to copy elements from one array to another.

const fruits = ['Cherry', 'Orange', 'Apple', 'Grapes'];
const fruitsCopy = [...fruits];

console.log(fruitsCopy) // Output: [ 'Cherry', 'Orange', 'Apple', 'Grapes' ]
console.log(fruits === fruitsCopy); // Output: false

Using the slice() method:

The slice() method is used to copy a portion of an array into a new array. If you call it without arguments, it returns a copy of the entire array.

const fruits = ['Cherry', 'Orange', 'Apple', 'Grapes'];
const fruitsCopy = fruits.slice();

console.log(fruitsCopy) // Output: [ 'Cherry', 'Orange', 'Apple', 'Grapes' ]
console.log(fruits === fruitsCopy); // Output: false

Using the concat() method:

The concat() method merges two or more arrays. When you call it on an empty array and pass the source array as an argument, it creates a new array with the elements of the source array.

const fruits = ['Cherry', 'Orange', 'Apple', 'Grapes'];
const fruitsCopy = [].concat(fruits);

console.log(fruitsCopy) // Output: [ 'Cherry', 'Orange', 'Apple', 'Grapes' ]
console.log(fruits === fruitsCopy); // Output: false

3: Remove duplicates from arrays

Nice one-liner to quickly remove duplicates from an array without using loops.

const names = ['Mark', 'Robert', 'Tom', 'Mark', 'Jack', 'Tom'];
const uniqueNames = [...new Set(names)];

console.log(uniqueNames); // Output: [ 'Mark', 'Robert', 'Tom', 'Jack' ]

4: Setting default values

A regular way of setting up default values using the if statement:

let username = getUsername();

if (!username) {
    username = 'David';
}

However, you can simplify this by using a single line of code with either the logical OR operator || or the nullish coalescing operator ??.

Logical OR operator || takes the right operand in the case of a falsy value, which includes an empty string, 0, false, NaN, null or undefined:

const username = getUsername() || 'anonymous';

The nullish coalescing operator ?? takes the right operand only when the left side is set to null or undefined:

const username = getUsername() ?? 'anonymous';

5. Calculate code performance

Easily measure the performance of your code using performance.now():

const start = performance.now();
// Your code
const end = performance.now();

const elapsed = end - start;
console.log(`Time: ${elapsed}ms`);

You can also use console.time() and console.timeEnd():

console.time('Time')
// Your code
console.timeEnd('Time')

That's all! I hope you find these JavaScript tips and tricks useful. Feel free to experiment and share your discoveries with the community. Happy coding!

Web DevelopmentJavaScript
Avatar for Patrick Hladun

Written by Patrick Hladun

I'm a Frontend Developer and WordPress enthusiast on a mission to constantly improve my skills and keep up with the latest technology trends.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.