6 Useful JavaScript Tips for Beginners
Hardik Gohil
Posted on March 5, 2023
Hey Guys, Hope you all are doing well. Here are some of the useful tips that can improve productivity and overall performance of JavaScript code. These tips are for beginner and intermediate programmers as well. So without further ado let's jump in!
Ternary Operator
// Don't Do this
let port;
if(process.env.PORT) {
port = process.env.PORT;
} else {
port = 8080;
}
// Do This
const port = process.env.PORT || 8080;
Template Literals
// Don't Do this
const greeting = 'Welcome Back ' + firstName + ' ' + lastName;
const successMessage = 'Your Product ' + productName + ' has been delivered on ' + orderDate + ' successfully!';
// Do This
const greeting = `Welcome Back ${firstName} ${lastName}`;
const successMessage = `Your Product ${productName} has been delivered on ${orderDate} successfully!`;
Check if the value is undefined or null - Nullish coalescing
// Don't Do This
const userInfo = {};
let userName = '';
if(user.name === undefined || user.name === null) {
userName = 'User not found!';
} else {
userName = user.name;
}
// Do This
const userInfo = {};
let userName = user.name ?? 'User not found!';
Read more about Nullish Coalescing Operator from Official Docs.
Converting string to number
// Don't Do This
const age = parseInt('22');
const qauntity = parseFloat('11.02');
// Do This
const age = +'22';
const qauntity = +'11.02';
Array/Object Destructuring
// Given
const project = {
name: 'Dribble Shot Design',
reporter: 'John Doe',
dueDate: '2023-03-05',
status: 'pending'
};
// Don't Do This
const projectName = project.name;
const projectReporter = project.reporter;
const projectDueDate = project.dueDate;
const projectStatus = project.status;
// Do This
const { name, reporter, dueDate, status } = project;
Implicit Boolean Coercion
// Don't Do This
const orderInfo = {} ;
let isOrderInfoAvailable;
if(Object.keys(orderInfo).length) {
isOrderInfoAvailable = true;
} else {
isOrderInfoAvailable = false;
}
// Do This
const orderInfo = {};
const isOrderInfoAvailable = !!orderInfo;
console.log(isOrderInfoAvailable); // true
Thanks for reading, If you liked the post please share it and leave suggestions.
Connect With Me
Website: Hardik Gohil
Github: https://github.com/HardikGohilHLR
Linkedin: https://www.linkedin.com/in/hardikgohilhlr
Thanks ❤️
💖 💪 🙅 🚩
Hardik Gohil
Posted on March 5, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.