1. The Ternary Operator:
// ❌ Not-so-good
let hungry = true;
let eat;
if (hungry === true) {
eat = 'yes';
} else {
eat = 'no';
}
// ✅ BETTER
let hungry = true;
let eat = hungry === true ? 'yes' : 'no';
Utilizing the ternary operator enhances code conciseness, making it more readable and efficient.
2. Populating an Array:
// ❌ Not-so-good
for(let i=0; i < arraySize; i++){
filledArray[i] {'hello' : 'goodbye'};
}
// ✅ BETTER
let filledArray = new Array(4).fill(null).map(()=> ({'hello' : 'goodbye'}));
console.log(filledArray);
Leveraging array methods like fill
and map
provides a cleaner and more idiomatic approach to array creation.
3. Dynamic Properties in Objects:
// ❌ Not-so-good
let dynamic = "value";
let user = {
id: 1,
};
user[dynamic] = "other value";
// ✅ BETTER
let dynamic = "value";
let user = {
id: 1,
[dynamic]: "other value"
};
Embracing computed property names enhances code expressiveness and maintains clarity.
4. Array to Object:
// ❌ Not-so-good
let arr = ["value1", "value2", "value3"];
let arrObject = {};
for (let i = 0; i < arr.length; ++i) {
if (arr[i] !== undefined) {
arrObject[i] = arr[i];
}
}
// ✅ BETTER
let arr = ["value1", "value2", "value3"];
let arrObject = {...arr};
// Output: { '0': 'value1', '1': 'value2', '2': 'value3' }
Using the spread operator simplifies the process of converting an array to an object.
5. Short Circuit Conditionals:**
// ❌ Not-so-good
if (docs) {
goToDocs();
}
// ✅ BETTER
docs && goToDocs();
Short-circuiting provides a concise way to handle conditional execution based on truthy values.
6.Object keys are stored in insertion order
const obj = {
name: "Rahul",
age: 16,
address: "Earth",
profession: "Developer",
};
console.log(Object.keys(obj)); // name, age, address, profession
7.Check if value is an array
const arr = [1, 2, 3];
console.log(typeof arr); // object
console.log(Array.isArray(arr)); // true
8.Difference between double equal and triple equal
// Double equal - Converts both the operands to the same type and then comapares
console.log(0 == '0'); // true
// Triple Equal - Does not convert t same type
console.log(0 === '0'); // false
9.Truthy and False values
False values => false, 0, ""(empty string), null, undefined, &NaN.
Truthy values => "Values", "0", {}(empty object), &[](empty array)
Enhance your JavaScript coding style by incorporating these practices for improved readability and efficiency. #JavaScript #CodingTips #WebDevelopment
Top comments (0)