33
Writing a JavaScript Code
We are used to writing JavaScript code for a long time. But we are not updated enough to use an optimized way of coding for JavaScript. With the optimized method of coding, we can be on top of the things which is related to optimized code. With Shorthand methods, lots of things become easy for developers, Like Error tracking, Code management, line of Codes, etc.
Here the list of javascript shorthands
- Javascript Shorthand for if with multiple OR(||) conditions
- Javascript Shorthand for if with multiple And(&&) conditions
- Javascript Shorthand for checking null, undefined, and empty values of variable
- Javascript Shorthand for switch case to select from multiple options
- Javascript Shorthand for functions for single line function
- Javascript Shorthand for conditionally calling functions
- Javascript Shorthand for To set the default to a variable using if
- Javascript Shorthand for if…else statements
- Javascript Shorthand for traditional for loops to fetch a value from array
- Javascript Shorthand for typecasting, Converting string to number
if (car === 'audi' || car === 'BMW' || car === 'Tesla') {
//code
}
In a traditional way, we used to write code in the above pattern. but instead of using multiple OR conditions we can simply use an array and includes. Check out the below example.
if (['audi', 'BMW', 'Tesla', 'grapes'].includes(car)) {
//code
}
if(obj && obj.tele && obj.tele.stdcode) {
console.log(obj.tele .stdcode)
}
Use optional chaining (?.) to replace this snippet.
console.log(obj?.tele?.stdcode);
if (name !== null || name !== undefined || name !== '') {
let second = name;
}
The simple way to do it is...
const second = name || '';
switch (number) {
case 1:
return 'Case one';
case 2:
return 'Case two';
default:
return;
}
Use a map/ object
const data = {
1: 'Case one',
2: 'Case two'
};
//Access it using
data[num]
function example(value) {
return 2 * value;
}
Use the arrow function
const example = (value) => 2 * value
function height() {
console.log('height');
}
function width() {
console.log('width');
}
if(type === 'heigth') {
height();
} else {
width();
}
Simple way
(type === 'heigth' ? height : width)()
if(amount === null) {
amount = 0;
}
if(value === undefined) {
value = 0;
}
console.log(amount); //0
console.log(value); //0
Just Write
console.log(amount || 0); //0
console.log(value || 0); //0
let label;
if (amt > 0) {
label = 'profit';
} else {
label = 'loss';
}
Replace it with a ternary operator
const label = amt > 0 ? 'profit' : 'loss';
const arr = [1, 2, 3];
for(let i=0; i<arr.length; i++) {
console.log(arr[i]);
}
Replace for with forEach
const arr = [1, 2, 3];
arr.forEach((val) => console.log(val));
const num1 = parseInt("100");
const num2 = parseFloat("11.11");
simply use + operator
const num1 = +"100";
const num2 = +"11.11";
33