Everyone has twenty-four hours a day.
We cannot create more time than that number but we can use it efficiently every single second.
One way to do this is to shorten your code with the following 15 techniques.
If it does not make sense, don’t declare each variable on every single line. One line is enough, save your spaces.
Instead of:
let name;
let price = 12;
let title;
let discount = 0.3;
Do this:
let name, price = 12, title, discount = 0.3;
I think this is so obvious but as long as it serves the subject, I put it in.
Instead of:
if (isUsernameValid === true) {}
if (isExist === false) {}
Do this:
if (isUsernameValid) {}
if (!isExist) {}
1000000 can cause some bugs if you miss one or two zero. The more zero in the tail, the more attention you have to pay. Fortunately, you don’t have to do that. Instead of writing 1000000, you can just shorten it to 1e6. The 6 represents the number of zeros in the tail.
Instead of:
let length = 10000;
for (let i = 0; i < length; i++) {}
Do this:
let length = 1e4;
for (let i = 0; i < length; i++) {}
Sometimes you have to define a function with multiple parameters. Do you need to pass all the parameters values every time you invoke the function? Not really if you initialize the default values.
Instead of:
let generateBookObject = (name, price, discount, genre) => {
let book = { name, price, discount, genre };
return book;
};
let book = generateBookObject(‘JavaScript’, 12, 0.3, ‘Technology’); // { name: ‘JavaScript’, price: 12, discount: 0.3, genre: ‘Technology’ }
Do this:
let generateBookObject = (name = ‘JavaScript’, price = 12, discount = 0.5, genre = ‘Technology’) => {
let book = { name, price, discount, genre };
return book;
};
// In case discount and genre are the same as the default values, you don’t need to pass them to the function
let book = generateBookObject(‘JavaScript’, 12); // { name: ‘JavaScript’, price: 12, discount: 0.5, genre: ‘Technology’ }
If there’s only one else in the conditional statement, shrink it to one line using ternary.
Instead of:
let name = ‘Amy’;
let message;
if (name === ‘Amy’) {
message = ‘Welcome back Amy’;
} else {
message = ‘Who are you?’;
}
Do this:
let name = ‘Amy’;
let message = name === ‘Amy’ ? ‘Welcome back Amy’ : ‘Who are you?’;
#programming #coding #javascript #javascript-tips