DEV Community

Cover image for 18 JavaScript Tips : You Should Know for Clean and Efficient Code
Shefali
Shefali

Posted on • Originally published at shefali.dev

18 JavaScript Tips : You Should Know for Clean and Efficient Code

In this post, I’ll share 18 JavaScript tips, with examples that you should know for writing clean and efficient code.

Let’s get started!🚀

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

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', '!']
Enter fullscreen mode Exit fullscreen mode

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

Output:

Console.table()

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

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

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

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

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

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

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

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

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

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

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

Template Interpolation

Utilize template literals for string interpolation and enhanced code readability.

For example:

const name = 'John';
const message = `Hello, ${name}!`;
Enter fullscreen mode Exit fullscreen mode

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

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

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

That’s all for today.

I hope it was helpful.

Thanks for reading.

For more content like this, click here.

You can also follow me on X(Twitter) for getting daily tips on web development.

Keep Coding!!
Buy Me A Coffee

Top comments (9)

Collapse
 
thomasg77 profile image
Thomas Gratier

For your section "Set Default Values with Logical OR Operator", instead use the following

function greet(name = 'Person') {
  console.log(`Hello, ${name}!`);
}

greet(); //Output: Hello, Person!
greet("John"); //Output: Hello, John!
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dantheman profile image
Daniel Engelhardt

May I respectfully disagree with "Set Default Values with Logical OR Operator"? The logical OR (||) is considered unsafe in certain use cases. I have a post up that's covering this topic: hardnold.hashnode.dev/why-you-shou...

Collapse
 
devshefali profile image
Shefali

Thanks for your feedback, Daniel!

Collapse
 
tony972 profile image
Taxman972

Great article, thanks for sharing.
Just a suggestion Spread Operator should be before Remove Array Duplicates since the operator is used in the second example.

Collapse
 
devshefali profile image
Shefali

Thanks for your suggestion.

I appreciate it 😊

Collapse
 
jpquinto profile image
Jeremy Quinto

I don’t know how I’ve never thought of or come across swapping variables using destructuring LOL

Collapse
 
devshefali profile image
Shefali

Yeah, this can be helpful sometimes. Thanks for checking out.

Collapse
 
devluc profile image
Devluc

Learned a lot from the article. Great work Shefali

Collapse
 
devshefali profile image
Shefali

Thank you so much, Lucian!

I'm happy to know that 😊

Some comments may only be visible to logged-in visitors. Sign in to view all comments.