JavaScript Tricks
Nashmeyah
Posted on April 5, 2021
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,
It can look cleaner like this,
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();
}
can be changed to,
hungry && goToFridge()
or,
if(age > 5){
kindergarten()
}else{
firstGrade()
}
transformed to this,
age > 5 ? kindergarten() : firstGrade()
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]
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.
Posted on April 5, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.