DEV Community

Pratham Srivastava
Pratham Srivastava

Posted on

✔9 Tricks For Enhancing JavaScript Code Readability and Efficiency

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';
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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"
};
Enter fullscreen mode Exit fullscreen mode

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' }
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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", 
}; 
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

9.Truthy and False values

False values => false, 0, ""(empty string), null, undefined, &NaN.

Truthy values => "Values", "0", {}(empty object), &[](empty array)
Enter fullscreen mode Exit fullscreen mode

Enhance your JavaScript coding style by incorporating these practices for improved readability and efficiency. #JavaScript #CodingTips #WebDevelopment

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️