1. Nullish coalescing operator (??)
The nullish coalescing operator (
??) is a logical operator that returns its right-hand side operand when its left-hand side operand is
undefined, and otherwise returns its left-hand side operand.
To understand this operator, let’s take an example.
quantity) and simply prints the total price. Something like this:
If we execute the code above, it will print the values in the browser console like this:
Pretty straightforward, right?
What if we call this function with
null values? It will simply do nothing and our logic might break. Let’s try this:
So it failed to perform the logic and we didn’t get the expected value, which is not what we wanted, right?.
To tackle this problem, developers usually use the || operator using the right-hand-side value if the left-hand-side value is
undefined. Which is fine. But the problem with || is that it considers
0 and a blank string as
To tackle this issue, we can use the nullish coalescing operator (
??), which works similarly to the || operator, but it doesn’t consider
0 and a blank string as
Now let’s run our previous code with
It prints the value as expected. So use
?? if you ever face a similar situation.
2. Apply CSS to Console Using %c
Developers know how important a browser console is. Whenever we have to check anything in our code, we simply print its value in the console.
If you have a huge application where there are tons of logs being printed out in the browser console. Styling your log message will make sure those important messages don’t get buried
Yes, this sounds crazy, but it’s very much possible. With the help of
%c, we can implement any CSS property on our console. We simply have to do this:
We just have to put
%c before the text that we want to style and pass the required CSS in the next parameter of the console.
Let’s try this on our previous example:
Well, now you know how that’s being created.
3. Use the Same Name As Object Key and Value
Let’s just take one more example to understand exactly what I’m trying to explain. Before everything else, let’s have a look at the following code:
We simply have two variables (name and city) and one object with two properties. If we execute this code, it will simply print the value of the details object in the browser’s console:
That’s all good. But if you noticed, the key of the object is the exact same as the name of the variable we are setting it to.
Instead of writing the same key and value variable name, we can simply combine them:
It will work exactly as before:
It’s a simple trick that saves you a bunch of space and makes your code looks cleaner.
Do try these tricks and let me know which one is your favorite. I hope this article was helpful. Thanks for reading!