DEV Community

Nashmeyah
Nashmeyah

Posted on

JavaScript Tricks

Hey Guys!

Here are a few JS tricks I learned online, I thought id share a few with you all.

Console.table()

When you have an array and you want to display the data, instead of it looking like this,
image

It can look cleaner like this,
image

the difference is the first one was used with console.log() and the second was used with console.table().

Conditionals

Within your code, you're likely going to use and if statement, now of course with this tip you'll want to use it carefully because we always want our code to be readable for other viewers. So in your code if you a simple if statement, you can use what is called a ternary operator.

Example:

if (tired) {
  sleep();
}
Enter fullscreen mode Exit fullscreen mode

can be changed to,

hungry && goToFridge()
Enter fullscreen mode Exit fullscreen mode

or,

if(age > 5){
  kindergarten()
}else{
  firstGrade()
}
Enter fullscreen mode Exit fullscreen mode

transformed to this,

age > 5 ? kindergarten() : firstGrade()
Enter fullscreen mode Exit fullscreen mode

Filtering for unique objects

Now we all know how many times we have had to filter out for unique elements, here is a trick using the Set object. "The Set object lets you store unique values of any type, whether primitive values or object references."(MDN, Online Doc)

const my_array = [1, 7, 2, 2, 3, 1, 4, 6, 5, 7, 8, 9, 1, 2, 4]
const unique_array = [...new Set(my_array)];
console.log(unique_array); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
Enter fullscreen mode Exit fullscreen mode

Thank you for enjoying my blog, I will post more tips more in the future if this was helpful. Once again, please let me know if there is anything you would like me to write about.

Top comments (0)