DEV Community 👩‍💻👨‍💻

Cover image for 7 Must Know JavaScript Tips & Tricks 🎈
Dom (dcode)
Dom (dcode)

Posted on

7 Must Know JavaScript Tips & Tricks 🎈

Let's have a look at 7 valuable tips and tricks found in the most popular language in the world, JavaScript.

1. Destructuring with Parameters

You can use object destructuring within function parameters. A popular use case for this would be something like event listeners, and gaining access to the target property on the event object.

buttonElement.addEventListener("click", ({ target }) {
    // is the same as using e.target 👇
    console.log(target);
});
Enter fullscreen mode Exit fullscreen mode

2. Deep Copy with JSON

You may have heard of using object spread or Object.assign() to make shallow copies of an object, but did you know about using JSON to make deep copies?

Simply convert an object to JSON using JSON.stringify() and then re-parse it using JSON.parse() to create a deep copy.

Just remember to only do this for simple objects, as doing it on large objects may raise performance issues.

const person = {
    name: "Dom",
    age: 28,
    skills: [
        "Programming",
        "Cooking",
        "Tennis"
    ]
};

const copied = JSON.parse(JSON.stringify(person));

// false 😎
console.log(person.skills === copied.skills);
Enter fullscreen mode Exit fullscreen mode

3. Easy Defaults with OR

I talk about this one a lot. Basically, you can use the logical OR operator (||) for defaults as opposed to using an if statement.

Alternatively, for stricter comparisons, you can take advantage of the nullish coalescing operator

Old Code (using if statement - 4 lines)

let username = getUsername();

if (!username) {
    username = "Dom";
}
Enter fullscreen mode Exit fullscreen mode

New Code (using || - 1 line)

const username = getUsername() || "Dom";
Enter fullscreen mode Exit fullscreen mode

The new code also means you can use const over let.

4. Advanced Array Searching

Step aside, indexOf() and includes() because there's another method that allows for advanced array searching and it's called find().

The find() method allows you to pass in a test function. The first element within the array to pass the test function will be returned.

This makes for more useful array searching.

const occupations = [
    "Lawyer",
    "Doctor",
    "Programmer",
    "Chef",
    "Store Manager",
];

const result = occupations.find(o => o.startsWith("C"));

// "Chef" 🧑‍🍳
console.log(result);
Enter fullscreen mode Exit fullscreen mode

5. Remove Array Duplicates

You may have heard of this one before, but there's a really simple way to remove duplicates from an array using the Set data structure.

Basically, Set doesn't allow duplicate values. We can take advantage of that by turning an array into a Set, and then back into an array.

const numbers = [5, 10, 5, 20];
const withoutDuplicates = Array.from(new Set(numbers));

// [5, 10, 20] 👇
console.log(withoutDuplicates);
Enter fullscreen mode Exit fullscreen mode

6. Self-Invoking Functions

This one is a classic. Self-invoking functions are functions that execute themselves. A common use case for these is to assign a variable or constant that requires complex logic.

const someComplexValue = (() => {
    const a = 10;
    const b = 20;

    if (a > b) {
        return a * b;
    }

    return b / a;
})();
Enter fullscreen mode Exit fullscreen mode

Of course, the above example is trivial but you can imagine the kind of complex code you may require to be within the self-invoking function.

7. Array Copying with Spread

Last on this list involves creating shallow copies of an array. We can do this using spread (...).

const numbers = [5, 19, 24, 36];
const numbersCopy = [...numbers];

// false
console.log(numbers === numbersCopy);
Enter fullscreen mode Exit fullscreen mode

I hope you learnt at least something new from this list. For more JavaScript content, check out my YouTube channel, dcode.

Enrol Now 👉 JavaScript DOM Crash Course

If you're learning web development, you can find a complete course on the JavaScript DOM at the link below 👇
https://www.udemy.com/course/the-ultimate-javascript-dom-crash-course/?referralCode=DC343E5C8ED163F337E1

Course Thumbnail

Top comments (16)

Collapse
 
lukeshiru profile image
Luke Shiru

A few corrections:

Cheers!

Collapse
 
vhoyer profile image
Vinícius Hoyer

That was exactly what I was going to comment, thanks

Collapse
 
orimdominic profile image
Orim Dominic Adah

Structured clone does not work in Node.js

Collapse
 
lukeshiru profile image
Luke Shiru

Yes it does, since October of last year (Node 17). So unless you're using a jurassic version, it should be in your Node environment.

Thread Thread
 
orimdominic profile image
Orim Dominic Adah

I don't see how 14 and 16 are 'jurassic' versions. 18 is the latest.
Thanks for the update though

Thread Thread
 
lukeshiru profile image
Luke Shiru

14 is in maintenance mode (meaning you should be switching to a more modern version ASAP) and was released more than 2 years ago, and 16 was released more than a year ago and is the LTS but the support ends in 1 month (October 2022), making 18 the current LTS. I exaggerated a bit with "jurassic", but if we care about support, features and security, we should avoid using software that is 1+ years old (all my homies are using Node 17 or 18). Same applies to packages that weren't updated for years.

Thread Thread
 
camiloforero profile image
camiloforero

In production environments, either Active LTS (16) or Maintenance LTS (14) should be used.

Node 18 is not an LTS at all, it's the Current release, and it is not quite fit for production use until the 25th of october, when it will become Active LTS

It's all here: github.com/nodejs/release#release-...

Thread Thread
 
lukeshiru profile image
Luke Shiru • Edited on
  • 14 was released more than 2 years ago and is in maintenance LTS, which means it doesn't have active support, it only has security support (and for other 7 months).
  • 16 was released more than 1 year ago, is the current LTS, but is about to end (active support ends in October 18th), and it will have security support for other 11 months tho is recommended to start switching to the coming LTS which will have active support.
  • I didn't said 18 IS the LTS, I said 18 WILL BE the LTS in a month, when active support for 16 ends. 18 was released just a few months back, and it will have active support for a year.

Check this one better, which makes it really easy to follow: If is yellow, is a warning that you should be considering upgrading, red is bad, green is good.

Why are we even discussing this? Is a known fact that you should keep your environment up-to-date 😵

Collapse
 
caominhdev profile image
Cao Quốc Minh

(y)

Collapse
 
thomasbnt profile image
Thomas Bnt

Nice !
You can put video embed with :

{% embed https://www.youtube.com/watch?v=oRekCcwSeXs %}

Collapse
 
matijanovosel profile image
Matija Novosel

Excellent post, though for number 5 I'd note that using Set does indeed remove duplicates but only if the array is filled with primitive values.

In the case of an array being filled with objects, however...

const departureTimes = [{"departureTime": "07:00:00"}, {"departureTime": "07:00:00"}, {"departureTime": "13:05:00" }];
const unique = Array.from(new Set(departureTimes)); // [{"departureTime":"07:00:00"},{"departureTime":"07:00:00"},{"departureTime":"13:05:00"}]
Enter fullscreen mode Exit fullscreen mode

A little overkill but In this case something like this could also work:

const unique = Array.from(new Set(departureTimes.map(x => JSON.stringify(x)))).map(x => JSON.parse(x)); // [{"departureTime":"07:00:00"},{"departureTime":"13:05:00"}]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
majklzumberi profile image
majkl zumberi

A deep clone now can be done with the native api structuredClone() it also clone deep nested objects

Collapse
 
adam_cyclones profile image
Adam Crockett

Did you also know that JSON parse and stringify have 2nd arguments, a function for filtering and processing all values

Collapse
 
pranav2580 profile image
Pranav Kumar

Thanks dude it is so amazing ☺️

Collapse
 
anirseven profile image
Anirban Majumdar

Thanks for this amazing article

Collapse
 
mobashir10 profile image
Mo Bashir

If all of these are copy from dcode tutorial what your course will be

Video link:
youtu.be/oRekCcwSeXs

Visualizing Promises and Async/Await 🤯

async await

☝️ Check out this all-time classic DEV post