Hey guys, In this article I would like to put some "line savers" and "time savers" basically JavaScript shorthand techniques that I think will be handy for many developers.
1. Short-circuit Evaluation
Checking a variable's value is bit common. lets see how we can save some lines and assign value to other variable
if (user !== null || user !== undefined || user !== '')
{
profile = user
} else
{
profile = "some default name"
}
line saver
let profile = user || 'some default name';
2. Declaring variables
we need to declare multiple variable one after other even though we know that javascript uses hoist to your variable declaration.
let user;
let org;
let age = 25;
line saver:
let user, org, age = 25;
3. String into a Number
built in methods like parseInt and parseFloat can be used to convert string into number but can also be done by simply providing an unary operator (+) in front of string value.
let aNumerical = parseInt('764');
let bNumerical = parseFloat('29.3');
time saver
let aNumerical = +'764';
let bNumerical = +'29.3';
4. Decimal base exponents
sometimes we need to write long values containing many zerooooooos. Instead we can use this saver
for (let i = 0; i < 10000; i++) {
...
}
time saver
for (let i = 0; i < 1e4; i++) {
...
}
5. Swap two variables
For swapping two variables, we often use a third variable. But it can be done easily and saves line with array de-structuring assignment.
let x = 'Hello', y = 'JS';
const temp = x;
x = y;
y = temp;
line saver
[x, y] = [y, x];
6. Merging of arrays:
spread operator solves many of the long hands one of them is merging two arrays, lets see how it saves us some lines:
let arrayBefore = [2, 3];
let arrayAfter = arrayBefore.concat([6, 8]);
// Output: [2, 3, 6, 8]
saver
let arrayAfter = [...arrayBefore , 6, 8];
// Output: [2, 3, 6, 8]
7. charAt()
This is straighforward
“SomeString”.charAt(0); //S
line saver
“SomeString”[0] //S
8 For Loop
we often use for loops to iterate, lets see the better way out
const countries = [“USA”, “Japan”, “India”]
for (let i = 0; i < countries.length; i++) {
...
}
line saver
for (let country of countries) {
...
}
9 The Ternary Operator
This is a great replacement for basic if...else condition
lets see how it save us some lines
const age = 25;
let allow;
if (age > 20) {
allow = true;
} else {
allow = false;
}
line saver
let allow = age > 20 ? true : false;
10. Arrow Function
Now this one is most important, JavaScript Arrow functions were introduced in ES6. other then having a shorter syntax it has other advantages as well. though its a separate topic to cover practice, just mentioning the basic usage
function add(a, b) {
return a + b;
}
line saver
const add = (a, b) => a + b;
I wanted to keep it short . Thank you for reading, I hope you found this helpful!
Top comments (0)