18 JavaScript Tips : You Should Know for Clean and Efficient Code
Tags: webdev, javascript, programming, beginners
Published: 2024-01-22 05:30:00

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:

```js
function add(a, b) {
  return a + b;
}

// Arrow function
const add = (a, b) => a + b;
```

## Array.from()

The `Array.from()` method can be used to convert any iterable objects into arrays.

```js
const str = "Hello!";
const arr = Array.from(str);

console.log(arr); //Output: ['H', 'e', 'l', 'l', 'o', '!']
```

## Display Data with console.table()

If you want your data organized or in tabular format in the console, then you can use `console.table()`.

```js
const person = {
    name: 'John', 
    age: 25,
    profession: 'Programmer'
}
console.table(person);
```
Output:

![Console.table()](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/si2hvhk7l064unqoddxy.png)

## Use const and let effieciently

Use `const` for variables that won’t be reassigned and `let` for those that will, for better code organization.

```js
const PI = 3.14;
let timer = 0;
```

## Extract Object Properties with Destructuring

By using destructuring to extract properties from objects, you can enhance code readability.

```js
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);
```

## Set Default Values with Logical OR Operator

Set default values easily using the `||` operator.

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

greet(); //Output: Hello, Person!
greet("John"); //Output: Hello, John!
```

## Effortlessly Empty an Array

You can empty an array easily by using the `length` property.

For example:

```js
let numbers = [1, 2, 3, 4];
numbers.length = 0;
console.log(numbers); //Output: []
```

## JSON.parse()

Use `JSON.parse()` to convert a JSON string into a JavaScript object, this ensures seamless data manipulation.

```js
const jsonStr = '{"name": "John", "age": 25}';
const person = JSON.parse(jsonStr);
console.log(person); 
//Output: {name: 'John', age: 25}
```

## Map() Function

Use the `map()` function to transform elements in a new array without modifying the original array.

For example:

```js
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]
```

## Object.seal()

You can use `Object.seal()` method to prevent adding or removing properties in the object.

```js
const person = {
    name: 'John', 
    age: 25
};
Object.seal(person);
person.profession = "Programmer";
console.log(person); //Output: {name: 'John', age: 25}
```

## Object.freeze()

You can use `Object.freeze()` method to prevent any changes to an object, including adding, modifying or deleting properties.

```js
const person = {
    name: 'John', 
    age: 25
};
Object.freeze(person);
person.name = "Mark";
console.log(person); //Output: {name: 'John', age: 25}
```

## Remove Array Duplicates

You can remove duplicate elements from an array using `Set`.

```js
const arrWithDuplicates = [1, 12, 2, 13, 4, 4, 13];
const arrWithoutDuplicates = [...new Set(arrWithDuplicates)];
console.log(arrWithoutDuplicates); 
//Output: [1, 12, 2, 13, 4]
```

## Swap values using Destructuring

You can swap two variables easily using destructuring.

For example:

```js
let x = 7, y = 13;
[x, y] = [y, x];
console.log(x); //13
```

## Spread Operator

You can copy or merge arrays efficiently using the spread operator.

For example:

```js
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]
```

## Template Interpolation

Utilize template literals for string interpolation and enhanced code readability.

For example:

```js
const name = 'John';
const message = `Hello, ${name}!`;
```

## Ternary Operator

You can simplify conditional statements with the ternary operator.

```js
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");
```

## Use === Instead of ==

Prevent type coercion issues by using strict equality (===) instead of loose equality (==).

```js
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');
}
```

## Use Descriptive Variable and Function Names

Use meaningful and descriptive names for variables and functions to enhance code readability and maintainability.

```js
// Don't declare variable like this
const a = 18;

// use descriptive names
const numberOfTips = 18;
```
That’s all for today.

I hope it was helpful.

Thanks for reading.

For more content like this, [click here](https://shefali.dev/blog).

You can also follow me on [X(Twitter)](https://twitter.com/Shefali__J) for getting daily tips on web development.

Keep Coding!!
<a href="https://www.buymeacoffee.com/devshefali" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" height="41" width="174"></a>