DEV Community 👩‍💻👨‍💻

DEV Community 👩‍💻👨‍💻 is a community of 968,873 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Kealan Parr
Kealan Parr

Posted on • Updated on

Useful JavaScript snippets

I often read some smart syntax a developer uses and have a "Aha!" moment. But if I don't immediately need to use it, it's very easy to forget it.

So I'll make sure I write them all down here from now on 😈

1# If you are comparing two objects (even nested objects) and they have the same property order, the fastest way to compare them is to serialize them and then compare them (the same goes for an ordered array) like:

let firstString  = JSON.stringify(obj1);
let secondString = JSON.stringify(obj2);
firstString === secondString;
Enter fullscreen mode Exit fullscreen mode

2# Writing the below

if (variable == null) {
}
Enter fullscreen mode Exit fullscreen mode

is the same as

if (variable === null || variable === undefined) {
}
Enter fullscreen mode Exit fullscreen mode

3#
You can build objects from truthy and falsy values, something like:

const obj = {
  ...(true) && {someprop: 42},
  ...(false) && {nonprop: "foo"},
  ...({}) && {tricky: "hello"},
}

console.log(obj); // {someprop: 42, tricky: 'hello'}
Enter fullscreen mode Exit fullscreen mode

4#
If you need to get a random, unique string (like for example a key for a React component), you can generate a random number, and from the random number, turn it into a string with a radix:

(Math.random() * 100).toString(36) // t.b4m6wbai1
(Math.random() * 100).toString(36) // 26.ouhmguf
(Math.random() * 100).toString(36) // p.dl8iau9cl
(Math.random() * 100).toString(36) // 1w.mcuqns82l
Enter fullscreen mode Exit fullscreen mode

5#
You can use an _ inside an arrow function to omit the () if there are no arguments, for example:

let a = 4;
let b = 2;
(() => a + b + 100)()
Enter fullscreen mode Exit fullscreen mode

is equivalent to

let a = 4;
let b = 2;
(_ => a + b + 100)()
Enter fullscreen mode Exit fullscreen mode

6#
You can trace an codes call-stack in the console easily by generating an error, like

console.log(Error('this is where it calls'))
Enter fullscreen mode Exit fullscreen mode

7#
You can add functions to the window if you want to "play" around and see what different things they return

8#
If you need to group console log's together you can use console.group like so:

console.group()
for(var i=0; i < 5; i++){ console.log('these will be grouped') }
console.groupEnd()
Enter fullscreen mode Exit fullscreen mode

A picture of the Chrome dev console with groups delimiting the logs

Top comments (0)

Now it's your turn.

Join DEV and share your story.