These JavaScript Tricks and Tips Everyone Should Know π
I wish I had known these tricks and methods earlier
JavaScript is the most used programming language for web development. You can use JavaScript for frontend (React.js, Vue.js), backend (Node.js), mobile app (React Native), and desktop app (Electron.js) development.
JavaScript is easy to learn but challenging to master. I will share some useful JavaScript tips, tricks and methods in this story with you. Whether you are a beginner or an experienced developer, these tricks will make your development process easier and boost your productivity.
1. Use the β??β (Nullish Coalescing Operator)
The ?? operator returns a default value for a null or undefined value. It is useful when dealing with false values like 0 and β.β
const firstName = "Gyan";
const lastName = "";
const age = 0;
const isActive = false;
const email = null;
const userName = undefined;
const defaultValue = "defaultValue";
console.log(firstName ?? defaultValue); // "Gyan"
console.log(lastName ?? defaultValue); // ""
console.log(age ?? defaultValue); // 0
console.log(isActive ?? defaultValue); // false
console.log(email ?? defaultValue); // "defaultValue"
console.log(userName ?? defaultValue); // "defaultValue"
Why Use It?
- It can help you to prevent unexpected null or undefined values from breaking your code.
- It is a better shorthand for userName !== null && userName !== undefined.
2. Optional Chaining with β?β
This is used to check nested object values without breaking the code.
const user = { profile: { address: { city: "New York" } } };
console.log(user.profile?.address?.city); // 'New York'
console.log(user.profile?.address?.country); // undefined
Why Use It?
- It can replace long if and && operator conditions to a single line. It makes code more readable and easy to write.
From-
if (user && user.profile && user.profile.address && user.profile.address.city) {
console.log(user.profile.address.city);
} else {
//
}
To-
console.log(user.profile?.address?.city);
3. Destructure with Defaults
You can destructure an array or object with a default fallback value if a particular does not exist.
const { name = "Anonymous", age = 18 } = { name: "Alice" };
console.log(name); // 'Alice'
console.log(age); // 18
In the above example, the object has a value for βnameβ. But as the value for βageβ does not exist, it will give 18 as the default value.
Why Use It?
- It can reduce the number of conditional checks.
- Write the clean code when handling large data.
4. String Interpolation
You can use variables in the string with the help of string interpolation.
const name = "Gyan";
const message = `Hello, ${name}! Welcome to JavaScript.`;
console.log(message); // 'Hello, Gyan! Welcome to JavaScript.'
Why Use It?
- You can get rid of string addition with the use of β+β.
- The code becomes more readable.
5. Spread Operator (β¦)
It is a useful operator for adding two arrays or creating a new array.
const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4, 5, 6]; // [1, 2, 3, 4, 5, 6]
You can also use the ββ¦restβ method to get the remaining elements from an array other than known elements.
const user = { name: "Gyan", age: 28, gender: "male", isActive: true };
const { name, age, ...rest } = user;
console.log(name); // "Gyan"
console.log(age); // 28
console.log(rest); // { "gender": "male", "isActive": true }
Why Use It?
- It makes easy to work with arrays and objects.
- It avoids the mutation of original data.
6. Array Using Set
Using the Set function, you easily remove duplicates from an array.
const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers) // [1,2,3,4,5]
Why Use It?
- It can remove duplicates in one line without using a loop.
- More readable and efficient than filtering an array using a loop.
7. Default Parameter Values in Functions
You can pass a default parameter in a function when the given argument is received as undefined.
const greet = (name = "Guest") => {
console.log(`Hello, ${name}!`);
};
greet(); // "Hello, Guest!"
greet("Gyan"); // "Hello, Gyan!"
Why Use It?
- It can avoid the error of an undefined argument.
- It makes function flexible and safe.
8. Object Property Swap
You can use object destructuring to swap object values.
let a = 5, b = 10;
[a, b] = [b, a];
console.log(a, b); // 10, 5
Why Use It?
- It reduces the need for temporary variables.
- It is a concise and elegant way to swap variables.
Conclusion
These JavaScript tricks can help you write clean and efficient code. I have been using these methods for very long. It reduces errors in my code and the number of lines.
Try these tricks and tips and improve your code quality.
Happy coding! π