Top 5 Techniques to make your javascript code look like a pro
- Ternary Operator
This is a great alternative if you just want to assign a value to a variable based on a condition, it has a simple syntax too
const age = 15; // Longhand
let message;
if (age > 18) {
message = "The person is an adult";
} else {
message = "The person is kiddo";
}// shorthand
const message = age > 18 ? "The person is an adult" : "The person is kiddo";
2. Alternate to switch
As there is an alternative to the IF condition, there is a similar alternative to the switch case. we can use an object with function names associated with the keys.
const something = 2;// normal switch case:
switch (something) {
case 1:
doSomething();
break;
case 2:
doSomethingElse();
break;
case 3:
doSomethingElseAndOver();
break;
}// alternative
cases = {
1: doSomething,
2: doSomethingElse,
3: doSomethingElseAndOver,
};cases[2]();
3. Get Rid of Multiple checks inside the if-condition
if (res === 25 || res === "twenty-five" || res === 25.0) {
// some action here
}// Shorthand if [25, "twenty-five", 25.0].includes(res)) {
// some action here
}
4. getting char at a particular position in a string
// old way
const randomString = "Prasanna"
console.log(randomString.charAt(0)); // P// shorthand
console.log(randomString[0]); // P
5. Destructuring
A lot of time I see in the code that a value is obtained using a dot notation and then stored in a variable, but there is a better way of doing this.
// Arrays
const numbers = [1, 2, 3, 4, 5];// Longhand
const one = numbers[0];
const two = numbers[1];
let others = [];
others.push(numbers[2]);
others.push(numbers[3]);
others.push(numbers[4]); // Shorthand
const [one, two, others] = numbers;
// Objectsperson = { name: "John",
age: 25,
city: "LA",
state: "California",
};// Longhand
const name = person.name;
const age = person.age;
const address = { city: person.city, state: person.state };// Shorthand
const { name, age, ...address } = person;
conclusion:
There are billion other ways of writing code, write code for a human not for a machine. Remember, do not overdo refactoring which might be nice for you but hell for the next developer. I hope you find these techniques to be helpful when you use them in your coding.