18 JavaScript Tips for Clean and Efficient Code
1. Arrow Function
You can use arrow functions to simplify function declarations.
For example:
function add(a, b) {
return a + b;
}
// Arrow function
const add = (a, b) => a + b;
2. Array.from()
The Array.from() method can be used to convert any iterable objects into arrays.
const str = "Hello!";
const arr = Array.from(str);
console.log(arr); //Output: ['H', 'e', 'l', 'l', 'o', '!']
3. Display Data with console.table()
If you want your data organized or in tabular format in the console, then you can use console.table().
const person = {
name: 'John',
age: 25,
profession: 'Programmer'
}
console.table(person);
Output:
4. Use const
and let
effieciently
Use const for variables that won’t be reassigned and let for those that will, for better code organization.
const PI = 3.14;
let timer = 0;
5. Extract Object Properties with Destructuring
By using destructuring to extract properties from objects, you can enhance code readability.
const person = {
name: 'John',
age: 25,
profession: 'Programmer'
}
//Instead of this 👇
console.log(person.name);
console.log(person.age);
//Use this👇
const {name, age} = person;
console.log(name);
console.log(age);
6. Set Default Values with Logical OR Operator
Set default values easily using the | operator. |
function greet(name) {
name = name || 'Person';
console.log(`Hello, ${name}!`);
}
greet(); //Output: Hello, Person!
greet("John"); //Output: Hello, John!
7. Effortlessly Empty an Array
You can empty an array easily by using the length property.
For example:
let numbers = [1, 2, 3, 4];
numbers.length = 0;
console.log(numbers); //Output: []
8. JSON.parse()
Use JSON.parse() to convert a JSON string into a JavaScript object, this ensures seamless data manipulation.
const jsonStr = '{"name": "John", "age": 25}';
const person = JSON.parse(jsonStr);
console.log(person);
//Output: {name: 'John', age: 25}
9. Map() Function
Use the map() function to transform elements in a new array without modifying the original array.
For example:
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(numbers); //Output: [1, 2, 3, 4]
console.log(doubled); //Output: [2, 4, 6, 8]
10. Object.seal()
You can use Object.seal() method to prevent adding or removing properties in the object.
const person = {
name: 'John',
age: 25
};
Object.seal(person);
person.profession = "Programmer";
console.log(person); //Output: {name: 'John', age: 25}
11. Object.freeze()
You can use Object.freeze() method to prevent any changes to an object, including adding, modifying or deleting properties.
const person = {
name: 'John',
age: 25
};
Object.freeze(person);
person.name = "Mark";
console.log(person); //Output: {name: 'John', age: 25}
12. Remove Array Duplicates
You can remove duplicate elements from an array using Set.
const arrWithDuplicates = [1, 12, 2, 13, 4, 4, 13];
const arrWithoutDuplicates = [...new Set(arrWithDuplicates)];
console.log(arrWithoutDuplicates);
//Output: [1, 12, 2, 13, 4]
13. Swap values using Destructuring
You can swap two variables easily using destructuring.
For example:
let x = 7, y = 13;
[x, y] = [y, x];
console.log(x); //13
14. Spread Operator
You can copy or merge arrays efficiently using the spread operator.
For example:
const arr1 = [1, 2, 3];
const arr2 = [9, 8, 7];
const arr3 = [...arr2];
const mergedArr = [...arr1, ...arr2];
console.log(arr3); //[9, 8, 7]
console.log(mergedArr); //[1, 2, 3, 9, 8, 7]
15. Template Interpolation
Utilize template literals for string interpolation and enhanced code readability.
For example:
const name = 'John';
const message = `Hello, ${name}!`;
16. Ternary Operator
You can simplify conditional statements with the ternary operator.
const age = 20;
//Instead of this👇
if(age>=18){
console.log("You can drive");
}else{
console.log("You cannot drive");
}
//Use this👇
age >= 18 ? console.log("You can drive") : console.log("You cannot drive");
17. Use === Instead of ==
Prevent type coercion issues by using strict equality (===) instead of loose equality (==).
const num1 = 5;
const num2 = '5';
//Instead of using ==
if (num1 == num2) {
console.log('True');
} else {
console.log('False');
}
//Use ===
if (num1 === num2) {
console.log('True');
} else {
console.log('False');
}
18. Use Descriptive Variable and Function Names
Use meaningful and descriptive names for variables and functions to enhance code readability and maintainability.
// Don't declare variable like this
const a = 18;
// use descriptive names
const numberOfTips = 18;