Awesome JavaScript Smart Techniques.
1.Ternary Operator
This is a great code saver when you want to write an if..else statement in just one line.
Longhand:
const x = 100;
let answer;
if (x > 100) {
answer = 'greater than 100';
} else {
answer = 'less than 100';
}
Shorhand
const answer = x > 100 ? 'greater than 100' : 'less than 100';
2.Short-circuit Evaluation
When assigning a variable value to another variable, you may want to ensure that the source variable is not null, undefined or empty.
Longhand:
if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
let variable2 = variable1;
}
Shorhand
const variable2 = variable1 || 'new';
3.Loop
This little tip is really useful if you want to perform iteration.
Longhand:
for (let i = 0; i < allImgs.length; i++)
Shorhand
for (let index of allImgs)
4.Object Property
Object literals in ES6 provides an even easier way of assigning properties to objects.
Longhand:
const obj = { x:x, y:y };
Shorhand
const obj = { x, y };
5.Arrow Functions
Classical functions are easy to read and write, but they do tend to become a bit confusing once you start nesting them in other function calls.
Longhand:
function sayHello(name) {
console.log('Hello', name);
}
setTimeout(function() {
console.log('Loaded')
}, 2000);
list.forEach(function(item) {
console.log(item);
});
Shorhand
sayHello = name => console.log('Hello', name);
setTimeout(() => console.log('Loaded'), 2000);
list.forEach(item => console.log(item));