This article collects some common javascript techniques for clean code and better development efficiency
1. Converting string to number.
We might be using Number() and parseInt() to convert string to number. But we can use "+" as well:
Example:
const str = '123';
const num = +str
2. Converting number to string
There is another method to convert number to string.
Example:
const num = 123;
const str = ""+num
But considering readibility and performance, String() and template string are recommended.
3. Ternary operator
The ternary operator is a shorthand way of writing an if-else statement in JavaScript. It is represented by the ? and : symbols, and has the following syntax:
condition ? expression1 : expression2
Example using if/else statement:
let num = 5;
let message;
if (num > 0) {
message = "Positive";
} else {
message = "Non-positive";
}
console.log(message); // Output: "Positive"
The same code can be written using the ternary operator as follows:
let num = 5;
let message = (num > 0) ? "Positive" : "Non-positive";
console.log(message); // Output: "Positive"
4. Use object instead of "switch"
We often use switch to handle different things, but have you ever thought of using an object to greatly simplify your code? Let me explain in code.
const n = 1
let result;
switch (n) {
case 1:
result = 'res-1'
break
case 2:
result = 'res-2'
break
case 3:
result = 'res-3'
break
// ...There are a lot more
}
We only need to use object map to achieve our goal:
const n = 1
const nMap = {
1: 'res-1',
2: 'res-2',
3: 'res-3'
}
const result = nMap[ n ]
5. Use the "includes" method instead of multiple "if"
We often writes code like this but multiple conditions makes the logic more confusing.
Example:
const n = 1
if (n === 1 || n === 2 || n === 3 || n === 4 || n === 5) {
// ...
}
Let's use "includes" method to make our code extra clean and maintainable:
const n = 1
const conditions = [ 1, 2, 3, 4, 5 ] // You just need to add new numbers here
if (conditions.includes(n)) {
// ...
}
6. Use the default parameters of the ES6 function
Example:
const func = (name) => {
name = name || 'magic'
console.log(name)
}
Let's use like this instead:
const func = (name = 'magic') => {
console.log(name)
}
7. Improve variable logging using console.log
Instead of using like this:
const str = "magic"
console.log("str:", str);
We can use like this to improve readability.
const str = "magic"
console.log({str});
This will print like an object with key as "str" and value as "magic".
8. Use of nullish coalescing operator with numbers
The Nullish Coalescing Operator (??) is a logical operator that accepts two values and returns the second value if the first one is null or undefined and otherwise returns the first value.
Example:
let num = 0;
let num2;
console.log(num || 1); // 1
console.log(num2 || 2); // 1
Let's use '??' operator now.
let num = 0;
let num2;
console.log(num ?? 1); // 0
console.log(num2 ?? 2); // 2
Hope you find these techniques useful and able to make your code cleaner. Happy reading!!
Top comments (14)
One interesting point in these cases of usefull techniques are two things:
Points to the first example:
There are good reasons why we use String() or .toString(). In these cases it is clear that the variable is changing its type. This is not so clear in
""+num
.From a reading point of view you are mixing two types, but you are not transforming it. In the end the JavaScript engine decides for you what it should become, and not you.
It also does not help others to figure out what that shortcut really does and could ask why you add an empty string to a number (if you read it literary) just to transform a number rather use optimised functions for transformation. I would like to ignore template literals in this case, as they have another use case.
What about performance?
You could also look up some benchmarks: measurethat.net/Benchmarks/Show/24...
There are even more benchmarks for this kind of tricks.
I don't say you should always use the best thing for performance, but using some weirdness of a language just because you can might hurt the readability and in the end maintainability.
Else, a nice read. Thanks and keep going π
Hi damian, thanks for the comment and putting the point on readability and performance. I have only pointed out some useful techniques which means we can also use them if we like to use. Im not saying it is best for performance. Infact, i mostly use String() and template string in my codes as well. Thanks again!!
Readability is completely subjective, and preaching it above all else can damage the quality of developers over time - sweeping features or 'weirdness' of a language under the carpet will only result in a diminishing understanding of that language and the various 'tricks' (for performance, brevity etc.) that are available.
Learn everything you can about a language and make your own decisions about what features are best to use in each situation. Don't bow to dogma.
Agreed. Thanks for the comment Jon!!
To convert numbers to strings, you can also use string templates:
This is a far more readable way to do it
There are few other methods as well. But template string is the one i mostly use as well. Thanks for reading!!
In the second example shouldn't the names be like this?
const num = 123;
const str = ""+num
My bad.It should be like this, i'll update. Thanks!!
In my opinion, first and second points looks so dirty
Might be, but these are only useful Techniques. So we need to use as per our case. Thanks for reading!!
useful
Thanks nikesh. I hope you liked it. Happy reading!!
Only 1 (I think) item here has anything to do with ES6