There are many developers who have a year or two of experience and ask themselves the following: How do I become a better developer? How do I go from being a middle- or beginner-level developer to the next level? The key is experience, but what is important about it is not time but what do you do in that time. Valuable experience is all about the knowledge you have and how well you apply it. This means you can hack the amount of experience by learning and putting into practice as many ideas as possible.
In this article you’ll learn some tricks that are not common for developers to learn. But most importantly, you’ll learn how to apply these tricks to real-world examples. This will help you grow your skills faster.
Code Readability
A good coder shouldn’t limit themselves to only writing code that works; they should write code that can stand the test of time. As you grow as a developer, you start to realize that, often, you won’t be there for any changes the code will need. The reasons are many, like switching jobs, or simply having to focus on other features while another coder works on your previous code. That’s why writing clear code becomes as important as the functionality of it.
You may have written a piece of code five years ago, and even to yourself now it seems it was written by an stranger. So it would be irresponsible to write code that sacrifices readability just for the sake of proving you know some weird hack of the language.
The tricks you’re about to learn are going to compress the code you’re writing under some circumstances; however, you shouldn’t abuse these tricks. Increasing readability is the actual objective of these tricks, as I’ll help you express the same ideas with less lines. Writing less code results in code that is more manageable, which you’ll appreciate as you jump to more complex and bigger codebases.
Overview
Because I want to focus on some weird but practical tricks, we’ll be looking at these operators:
-
&&
(the and operator)
-
||
(the or operator)
-
%
(the mod operator)
-
? :
(the ternary operators)
The And Operator
This operator might not be a stranger—you might have used it in the past to verify that multiple conditions are met. Like the following example:
if (bankAccount.amount > item.price && item.inventory >= shippingItem.qty) {
buy();
}
But when we use the &&
operator, the result isn’t necessarily true
or false
—it’s actually the value of the last condition that has been met. So we get a true value only in the case that all conditions are be considered truthy. Truthy is easier to define as the opposite of what is falsy. Falsy is a value treated as false for JavaScript, and that includes the following values:
null
undefined
false
0
""
NaN
This will give you an idea of how this works:
// 3 and 5 are not falsy so both conditions are truthy
3 && 5 // result: 5
This might look like a very useless thing to know; however, this is very powerful when you want to check if a value exists under an object which itself might or might not exist.
Let’s say you’re creating a component which has a config
object in which you might set a style
object to set the fontSize
. And let’s make the default fontSize
14 in case it isn’t set on the config
object.
The code to do that might look like the following:
var config = {
style: {
fontSize: 12
}
};
var fontSize = 14;
if (config.style) {
if (config.style.fontSize) {
fontSize = config.style.fontSize;
}
}
After applying the &&
operator and the ||
operator (which you’ll learn next) it reduces to:
var config = {
style: {
fontSize: 12
}
};
var fontSize = (config.style && config.style.fontSize) || 14;
Another powerful trick of this operator is that the second condition will only be executed if the first condition is truthy.
In our next example, let’s imagine your form component may have a callback function when it’s submitted, but this callback may or not exist. To call it, you might do the following:
if (this.onSubmit) {
this.onSubmit();
}
However, with the &&
operator, this gets reduced to:
this.onSubmit && this.onSubmit();
You don’t care about the result, you just care that the function gets executed in the case where it exists.
The Or Operator
Again, you might have used it under conditional statements, but also again, this operator can return something different from true
or false
. It returns the first truthy part.
// 24 and 45 are both truthy
24 || 45 // returns 24
This is very helpful to set default values on the code, but please note that this only works if a falsy value isn’t valid input. Let’s say we are working on a food platform and want to know how many ice cream cones a client wants. However, the default will be 1
. Using this operator, you’ll have the following:
var qty = order.ice_cream || 1;
So if the client orders one or more ice cream cones, the result will be correct. But if the client selects zero, the result will be one—please beware of this! In the case we explored before—about fontSize
—it works perfectly since zero isn’t expected as valid input.
This ||
operator combined with the &&
operator can verify the existence of an object, get the value, and in the case of non-existence, default to a predefined value.
The Conditional (Ternary) Operator ?:
Have you ever written an if
statement whose only purpose was to set a value on a variable depending if a condition is met? Let’s say, for example, you want to change the background color of a page depending on whether the user has a premium subscription. Your code might look like this:
if (user.premium){
this.headerBar.style.backgroundColor = colors.GOLD;
} else {
this.headerBar.style.backgroundColor = colors.BLUE;
}
There will be times when you’re facing this situation. Fortunately, the ternary operator can help you express the same thing in a more compact way. The operator has three parts:
- The condition
- Code that is returned if the condition is met
- Code that is returned if the condition is not met
So:
if (a) {
b;
} else {
c;
}
Will transform into:
a ? b : c
Back to our previous example using the ternary operator, the code can be rewritten as:
this.headerBar.style.backgroundColor = user.premium ? Colors.GOLD : Colors.BLUE;
Another use is formatting text depending on certain conditions, like if we have a price and we want to display it as a dollar amount or cents:
var priceText = (price < 1) ? ("$" + price.toFixed(2)) : (price * 100 + "¢");
The %
Operator
This one is a very strange operator, as it returns the remainder of a division operation. Let’s start by understanding how it works. Say you do 5 % 3
: If you divide 5/3
the result is 1
if you don’t calculate any decimals; your remainder will be 2
. Seems like it won’t have a lot of use until you start dealing with time.
Let’s say for example you’re building a stopwatch. If you search on the internet, you’ll see that most of the code out there tries to add the time that has passed by adding each second that has passed. This results in more complexity than needed.
We only need to know how much time has passed. Let’s say the current time is 150,678 ms, i.e., the time that’s passed since the stopwatch began to run. You’ll need to process that amount into minutes and seconds, which would be 02:30
. If you want to display how many minutes and seconds have passed, you can do the following:
var seconds = (currentTime / 1000); // get the total number of seconds
seconds = (seconds | 0); // take away the decimal part
// this will divide by 60 which will be the minutes and
// the remainder is the number of leftover seconds
seconds = (seconds % 60);
// using same approach to calculate minutes:
var minutes = ((currentTime / (60 * 1000)) | 0) % 60;
Another use of the %
operator is when dealing with next
and previous
functions that cycle when they reach the last item. Say you have a slideshow and the way you render a slide is by calling show(slideIndex)
, and you have an array with all the slides. Usually your next
function will look like this:
function next() {
if (this.currentIndex + 1 < this.slides.length) {
this.show(this.currentIndex + 1);
} else {
this.show(0);
}
}
Using the %
operator, that will be:
function next(){
this.show((this.currentIndex + 1) % this.slides.length);
}
Using All These Tricks Together
Using all that we have covered here, we can build a simple stopwatch with the following code in less than 30 lines of code:
function StopWatch(config){
// create config object in case none was sent
config = config || {}
// Read fontsize from config or set default to 12
var fontSize = (config.style && config.style.fontSize) || 12;
// Read color from config or set default to #000
var color = (config.style && config.style.color) || '#000';
var element = document.createElement('div');
// add the color and font size to the div
// that will hold our stopwatch
element.style.color = color;
element.style.fontSize = fontSize;
// Save when the stopwatch starts running
var startTime = new Date().getTime();
setInterval(function() {
// Calculate how much time has passed since
// the stopwatch started running
var currentTime = new Date().getTime() - startTime;
var seconds = Math.floor(currentTime / 1000) % 60;
var minutes = Math.floor(currentTime / (60 * 1000)) % 60;
seconds = (seconds < 10 ? '0' : '') + seconds;
minutes = (minutes < 10 ? '0' : '') + minutes;
element.innerHTML = (minutes + ':' + seconds)
}, 500);
return element;
}
document.body.appendChild(new StopWatch())
As you can see, the tricks I’ve discussed here have made it possible to write the same meaning in less lines of code. Now imagine this code is part of a huge project. If you can view the entire code, even with comments, without needing to scroll, then it will be easier to understand and modify.
However, I never went short on variable names, nor made this look like minified JS, which will have happen if we start changing element
to e
, or seconds
to s
. Using those names for variables will make you stop for a moment and think, In this context, what is e
or s
?
If you doubt whether you should apply one of these conciseness techniques, ask yourself the following: By making things this way, the next time I come to the code and view it with the eyes of a stranger, will it be easier or harder to understand? Happy coding!