Categories
Codes Javascript

20 JavaScript Tricks You Might Not Know Yet

“Only a mind free of impediment is capable of grasping the chaotic beauty of the world. This is our greatest asset.”

Oliver Bowden, Assassin’s Creed: The Secret Crusade

Introduction

I believe a beautiful code is a code that looks simple, but explains the logic and intention very clearly. Furthermore, it is clean and easy to read and understand.

JavaScript, with all its updates (now ES2020), has plenty of tricks that can be used to simplify some codes. Some you may have known already. Some which you don’t know yet might blow your mind.

In this post, I will share the cool tricks used in JavaScript which you also can use to write a simpler and cleaner code.


5 Conditional Tricks

Default Value Assignment

The logic is: “Return the value of this variable, if cannot, then return a default value”. The truth is, there are some ways you can accomplish these. And I believe the first time you learn to code, it would be something like this:

...
if (speak){
  word = speak;
}
else {
  word = "I don't speak";
}
...

Then, you would learn ternary operations. So it becomes this:

...
word = speak ? speak : "I don't speak";
...

OK, it looks better already, from five lines to just one line. But, it could get better:

...
word = speak || "I don't speak";
...

Yes, it is the current ultimate form of simplicity.

What happens is if speak variable has a false-y value (0, "", NaN, false, undefined, null), it will return the default variable which is "I don't speak".

Check If a Variable Is Not Falsy

A falsy variable has a value of one of these: 0, "", NaN, false, undefined, null. In a conditional statement, if the variable is not compared to anything, it will return false in JavaScript. Here is an example with the classical approach:

...
if (x === 0 || x == "" || x == NaN || x == undefined || x == null || x == false){
  console.log("it's false");
}
...

It’s quite long, isn’t it? You must make sure it satisfies all the falsy conditions. But, you can simplify it like this:

...
if (!x){
  console.log("it's false");
}
...

Cool.

Shorter Conditional Functions

Suppose that we have this conditional statement to execute a function:

if (x > 0){
  executeFunction();
}

It looks quite simple already, right? But, what if I can tell you it can be simpler? Here it is:

x > 0 && executeFunction();

Oh yes, it works. Just try it yourself.

This is a good trick if the condition statements are short and simple. Personally, I don’t use this trick much because I don’t want to sacrifice readability for coolness. Or maybe I would someday, after I force my teammates to read this post.

Quick Convert to Boolean

Sometimes, you also need to check whether the value of a variable is true and false only. And, false-y doesn’t count. The logic goes like this: “If this variable has a value, return true, otherwise return false.” Here is the longer example:

let exist = false;
if (something){
   exist = true;
}

It could be simplified to:

let exist = !!something;

Why not let exist = something? Because if something is a number or string or object, the variable exist‘s value won’t be a boolean.

Switch-Case With Numeric Ranges

You know the classic switch-case. But do you know that in JavaScript, numeric ranges can be used as cases? Here is an example:

let x = 20;
switch(true){
   case (x < 5): console.log("less than five"); break;
   case (x < 10): console.log("less than ten"); break;
   case (x < 15): console.log("less than fifteen"); break;
   case (x >= 20 && x < 25): console.log("less than twenty five"); break;
}

// Result: "less than twenty five"

2 Conversion Tricks

Convert a Number to String

There is a function in JavaScript to convert a number to string using toString(). And this function is very useful if you want to change the number to another base other than 10. But, if you mostly use base 10 numbers, there’s a cool trick by adding +"" at the end of the number. Then, it will become string. Here’s an example:

const x = 9;
console.log(x); // 9
console.log(x+""); // "9"
Convert a String to Number

When converting a string to number, the first thing that pops from our mind is by using Number or parseInt(). However, you can also use + at the beginning of the string to convert it to number. But, remember if the string cannot be parsed to a number, it will return as NaN. Let me show you an example:

const a = "1000";
console.log(a); // "1000"
console.log(+a); // 1000

const str = "something";
console.log(str); // "something"
console.log(+str); // NaN

2 Function Tricks

Self-Execute Function

Creating a function in JavaScript is one of the basics. You know this one:

...
const func = (a, b) => {
  let res = 0;
  res = res + a + b;
  res = res + a - b;
  res = res + a * b;
  console.log(res); // Result: 100
}

...

func(10, 8);

...

It requires you to declare the function and call it. But sometimes you want to separate the function, but you don’t want to move the function logic to the top or bottom of the script. So you can do it like this:

...
((a, b) => {
  let res = 0;
  res = res + a + b;
  res = res + a - b;
  res = res + a * b;
  console.log(res); // Result: 100
})(10,8);
...

It’s not that hard to see, you see.

You just have to add an opening and closing bracket on the function block. And add another opening and closing bracket for calling the function itself (the (10,8) part). And voila! The function is there, making a block of the code for you to notice the logic. And you don’t have to put the function to the top or bottom of the script.

Validate Parameter With a Function

It is always a good practice to set a default value for some parameters in a function. In JavaScript, you also can set the default value by using a method. See the example below:

const checkEmpty = () => { 
  throw new Error('Param must not be empty');
}

const log = (text = checkEmpty()) => {
   console.log("Result: " + text);
}

log("wow"); // "Result: wow"
log(); // error
log(null); // "Result: null"

It can be used to check whether the parameter is required or not, without writing the checker code inside the function. Cool!


4 Array Tricks

Every and Some

Many programmers are not familiar with these functions. every lets you to return true when every element in an array meets the conditions. some will return true when one element in an array meets the conditions. Here is an example:

const oddNums = [1,3,5,7,9,11,13,15];
const evenNums = [2,4,6,8,10,12,14,16];
const primeNums = [2,3,5,7,11,13,17];

const checkEven = (x) => {
  return x % 2 == 0;
}

oddNums.every(checkEven); // return false
oddNums.some(checkEven); // return false

evenNums.every(checkEven); // return true
evenNums.some(checkEven); // return true

primeNums.every(checkEven); // return false
primeNums.some(checkEven); // return true

There are no even numbers in oddNums, so it returns false for both functions.

In evenNums, all the numbers are even, so it returns true for both functions.

In primeNums.every(), not every number is even, so it returns false. But it returns true for some(), because there is a 2, which is an even number.

Get Array Unique Values

Just reading the section heading probably makes you think, “Damn, this one problem is not impossible to solve, but it might take rather long.” Tell you what, your life is getting easier from now on. Take a look at this example:

const arr = [1,2,3,3,5,8,8,true,true,"books","books","books",null,2];

const unique = [...new Set(arr)];

console.log(unique);
// [1, 2, 3, 5, 8, true, "books", null]

Yes, just use the Set native object, then use the spread operator (...) in an array. And, it’s done.

Sum All Values In An Array

You may feel that it’s easy to do, that there isn’t a trick about this. Just declare a let variable, set as 0, and then iterate all the values in the array then adding to the let variable, then you will get the result. Like this example:

const arr = [1,1,2,3,5,8,13,21,34];
let result = 0;

arr.forEach((v) => { result += v; });

console.log(result);

It does the job. But here’s a good trick:

const arr = [1,1,2,3,5,8,13,21,34];
const result = arr.reduce((res, v) => res + v);
console.log(result);

No need declaring a new variable. And it also does the job.

Sort Array of Numbers

The array in JavaScript has a sort function. But for numbers, it could result in a wrong order. Why? It’s because of something like this:

const arr = [1,42,84,13,101,24,451,8];
const res = arr.sort();

console.log(res); // [1, 101, 13, 24, 42, 451, 8, 84]

The numbers are converted as string. And therefore it returns as a sorted string, though the values are still numbers. So, to fix this problem, we must add a comparator function in the sort function:

const arr = [1,42,84,13,101,24,451,8];
const res = arr.sort((a,b) => a-b);

console.log(res); // [1, 8, 13, 24, 42, 84, 101, 451]

If you would like to sort as descending, change a-b to b-a.


5 Object Manipulation Tricks

Merge Multiple Objects

This trick is one of my favorites.

It is another of the magic use of spread operator (...). And it can be used to spread the properties of an object, as the properties of another new object. Therefore, by using multiple of them, you can also merge the properties of multiple objects to an object. See the example below:

const objectA = {
  test: 'true',
  amount: 10000
};

const objectB = {
  status: false,
  command: 'REDUCE',
  referenceId: "XYZ12345"
};

const objectC = {
  userId: 'aaa0000',
  name: 'Triple A Quadruple Zero',
  dob: 'today'
};

const mergedObject = {
  ...objectA, 
  ...objectB, 
  ...objectC 
};

console.log(mergedObject);
/* {
  amount: 10000,
  command: "REDUCE",
  dob: "today",
  name: "Triple A Quadruple Zero",
  referenceId: "XYZ12345",
  status: false,
  test: "true",
  userId: "aaa0000"
} */
Assign New Alias For Property On Destructuring

Sometimes, the same property’s value can have a different meaning between the input and processing. And then, you need to change the property’s name. For example:

...
const { humanId, dateOfBirth, savedMoney } = object;
const graveId = humanId;
const dateOfDeath = dateOfBirth;
const freeMoney = savedMoney;
...

The declaration of a new renamed variable can be simplified to this:

...
const {
 humanId: graveId,
 dateOfBirth: dateOfDeath,
 savedMoney: freeMoney 
} = object;
...

There’s no need to write const everything it’s assigned as a new variable on destructuring. That’s why I like it and I use it quite often.

Dynamic Property Name

There are some cases when you have to create a new object and you have to generate the properties from a source. And deep inside, you know you will feel much cooler if you manage to solve the problem with a beautiful solution. Here is an example:

const paramKey = 'color';
const paramValue = 'black';

const newObject = {
  comment: 'Black, or very very dark gray',
  [paramKey]: paramValue
};

console.log(newObject);
/*
{
  color: "black",
  comment: "Black, or very very dark gray"
}
*/

The downside is, your team mates probably have not read this post, so they don’t know about this trick yet.

Dynamically Call a Property In Object

Besides assigning a new dynamic property, you can also call a property in an object dynamically. Usually, we will use . to call a property, but in JavaScript you can call a property with an array syntax (If you learnt PHP before, it’s quite the same concept). Here is an example:

const obj = {
  name: 'Batman',
  value: 'Unlimited', 
  catchphrase: `Because I'm Batman!`
};

// usual property call
console.log(obj.name); // Batman

const prop = 'name';
// dynamic call
console.log(obj[`${prop}`]); // Batman

Actually obj[prop] can do the job also. But if you lint your code, which you should, it will show this error:

[eslint] Generic Object Injection Sink (security/detect-object-injection)

So, to pass the ESLint, change obj[prop] to obj[`${prop}`].

Iterate Object Properties

You can iterate the properties in an object in JavaScript, which is handy in some situations. There are two ways to do this, the first is using for-in, and the other is using Object.keys.

Here is an example of using for-in:

const obj = {
  name: 'Batman',
  value: 'Unlimited', 
  catchphrase: `Because I'm Batman!`
};

for (let key in obj) {
  let value = obj[`${key}`];
  console.log("Key: " + key, "Value: " + value);
}

/* Results: 
"Key: name", "Value: Batman"
"Key: value", "Value: Unlimited"
"Key: catchphrase", "Value: Because I'm Batman!"
*/

For-in will iterate all keys of the properties. And you can get the value by dynamically calling the property key.

And here is an example of using Object.keys:

const obj = {
  name: 'Batman',
  value: 'Unlimited', 
  catchphrase: `Because I'm Batman!`
};

Object.keys(obj).forEach((key) => {
  let value = obj[`${key}`];
  console.log("Key: " + key, "Value: " + value);
});

/* Results: 
"Key: name", "Value: Batman"
"Key: value", "Value: Unlimited"
"Key: catchphrase", "Value: Because I'm Batman!"
*/

Object.keys() will return an array of keys: name, value, catchphrase. And you can use any array iterator function to iterate the keys. Then, to get the value, see the “Dynamically Call Property In An Object” trick.


2 Other Cool Tricks

Format JSON for Output

I’m sure you know JSON.stringify(). But, you might not know that the function can be used to format the output. Because the parameter we use is only the first one: value.

To format the output, you have to know the other two optional parameters: replacer and space. space is the one to use. Set the replacer to null.

Let me show you an example before formatting:

const obj = {
  name: 'Batman',
  value: 'Unlimited', 
  catchphrase: `Because I'm Batman!`
};

const outputA = JSON.stringify(obj);
console.log(outputA);

/* Result:
"{\"name\":\"Batman\",\"value\":\"Unlimited\",\"catchphrase\":\"Because I'm Batman!\"}"
*/

Almost unreadable isn’t it? Now, here is the example with formatting:

const obj = {
  name: 'Batman',
  value: 'Unlimited', 
  catchphrase: `Because I'm Batman!`
};

const outputA = JSON.stringify(obj,null,'\t');
console.log(outputA);

/* Result
"{
    \"name\": \"Batman\",
    \"value\": \"Unlimited\",
    \"catchphrase\": \"Because I'm Batman!\"
}"
*/

Try this code yourself. The formatting works in console.

Promise.allSettled()

The last trick for now!

You might be already familiar with Promise.all(), which returns a Promise that fulfills when all the Promises has already been fulfilled. But Promise.all() will throw an error if one of the promises are rejected, and therefore will terminate the process of fulfilling midway, ignoring the already fulfilled and unfulfilled promises which were already made.

See the snippet below as an example for Promise.all():

const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = Promise.reject('error');
const promise4 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'foo');
});

const promises = [promise1, promise2, promise3, promise4];

Promise.all(promises).then((values) => {
  console.log(values);
}).catch((err) => { 
  console.log(err); 
});

// Actual output: "error"

From the example above, promise3 rejects, so it throws an error.

Promise.allSettled() will complete the promises, whether it resolves or rejects. The mantra is: “Run them all without caring the results.” The code snippet below explains more clearly:

const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = Promise.reject('error');
const promise4 = new Promise((resolve, reject) => {
  setTimeout(reject, 100, 'foo');
});

const promises = [promise1, promise2, promise3, promise4];

Promise.allSettled(promises).then((values) => {
  console.log(values);
});

// Output:
// Array [
//   Object { status: "fulfilled", value: 3 }, 
//   Object { status: "fulfilled", value: 42 }, 
//   Object { status: "rejected", reason: "Error" },
//   Object { status: "rejected", reason: "foo" }
// ]

promise3 and promise4 are rejected, but still settled as part of the returned Array.

Conclusion

Phew, I’m pretty sure you learnt quite a lot! I hope you can find it useful in your works!

And I’m also sure there’s still so many other tricks out there. Lastly, please let me know if you have another cool trick in JavaScript, just mention them in the comments!

Live it as your code, to code your life!

“If you think you’re smart, think twice to be smarter.”

― Toba Beta, Master of Stupidity

By Ericko Yap

Just a guy who is obsessed to improve himself. Working as a programmer in a digital banking company. Currently programming himself in calisthenics, reading books, and maintaining a blog.

Leave a Reply

Your email address will not be published. Required fields are marked *