10 JavaScript Shorthand Techniques To Improve Efficiency 💡
Tags: webdev, javascript, beginners, tutorial
Published: 2023-11-01 13:33:31


![Welcome](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ykg3ln7h20zin2ia1kxm.gif)

Hi friends! 👋 its me [Md Taqui Imam](https://tinyurl.com/MdTaquiImam), welcome to my new blog. 

Today I want to share <u>✨10 cool ways to shorten your JavaScript code</u> and make it more efficient. 

These tricks will help you write less code while still getting the job done ✔. 

**Let's get started!🔥**

## 1. Use `let` and `const` instead of `var` ✔️

The `let` and `const` keywords allow you to declare block scoped variables in JavaScript. This means the variable only exists within the nearby curly braces `{ }` instead of the whole function like `var` does. Less scope means less chances of bugs!

```js
// var is function scoped
var x = 1;

// let and const are block scoped 
{
  let y = 2;
  const z = 3;
}

console.log(x); // 1
console.log(y); // ReferenceError
console.log(z); // ReferenceError
```

## 2. Object Destructuring 📦

Destructuring lets you unpack values from arrays or properties from objects into distinct variables.

```js
// Old way
const user = { 
  name: 'John',
  age: 30
};

const name = user.name; 
const age = user.age;

// With destructuring
const { name, age } = user;
```

So much shorter!

## 3. Spread Syntax ...

The spread syntax `...` lets you expand arrays and objects. Useful for passing props or making copies without mutations.

```js
// Old way
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = arr1.concat(arr2); 

// With spread
const combined = [...arr1, ...arr2];
```

Easy! There are so many more use cases for spread too.

## 4. Template Literals ``

Template literals use backticks `` instead of quotes '' to create strings. They allow easier string interpolation like this:

```js
const name = 'John';

// Old way 
const greeting = 'Hello ' + name + ', how are you?';

// With template literal
const greeting = `Hello ${name}, how are you?`; 
```

No more concatenation!

## 5. Arrow Functions =>

Arrow functions provide a shorter syntax for writing function expressions.

```js
// Old way
function sum(a, b) {
  return a + b;
}

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

The syntax removes the need for `function` and `return` keywords in many cases.

## 6. Optional Chaining ?.

The optional chaining operator `?.` allows you to access nested properties on an object without throwing errors if the parent is undefined or null.

```js
const user = {
  name: 'John',
  address: {
    street: '123 Main St' 
  }
};

// Old way
const street = user.address && user.address.street;

// With optional chaining
const street = user.address?.street;
```

No more complicated logic!

## 7. Nullish Coalescing ??

The nullish coalescing operator `??` is similar to `||` but only considers `null` and `undefined` as falsy values. Useful for setting default values.

```js 
// Old way
const name = user.name || 'Guest'; 

// With nullish coalescing
const name = user.name ?? 'Guest';
```

## 8. Logical Operators && and ||

The logical operators can be used for shorthand conditionals by leveraging their boolean evaluation behavior.

```js
// Old way
let age = 25;
if (age >= 18) {
  drive();
}

// With Logical AND
age >= 18 && drive();

// Old way
if (!age) {
  age = 18;
}

// With Logical OR
age || (age = 18);
```

## 9. Array Methods map(), filter(), reduce() 🗺

These array methods provide simpler syntax for transforming, filtering, and reducing arrays to new values instead of traditional loops.

```js
const numbers = [1, 2, 3];

// Old way
const doubled = [];
for (let i = 0; i < numbers.length; i++) {
  doubled.push(numbers[i] * 2); 
}

// With map()
const doubled = numbers.map(n => n * 2);
```

So much more declarative! `filter()` and `reduce()` work similarly.

## 10. Ternary Operator ? :

The ternary operator provides shorthand syntax for basic if/else conditional logic.

```js
// Old way
let accessAllowed;
if (age > 18) {
  accessAllowed = true;
} else {
  accessAllowed = false;
}

// With ternary operator
const accessAllowed = age > 18 ? true : false;
```
## 🎉 Bonus 🎉 
## 11. DOM Manipulation abbreviations methods ⭐

- `addEventListener` → `addEvent` 
- `removeEventListener` → `removeEvent`
- `getElementById` → `getElem`
- `getElementsByTagName` → `getElems` 
- `classList` → `class`

For example:

```js
getElem('btn').addEvent('click', handleClick);
```

## String Methods

- `toUpperCase` → `toUpper`
- `toLowerCase` → `toLower` 
- `includes()` → `incl()`
- `indexOf()` → `indOf()`
- `substring()` → `substr()`
- `split()` → `spli()`

For example: 

```js
let name = 'johnDoe'.toLower();
```

## Array Methods 

- `push()` → `push`
- `pop()` → `pop`
- `shift()` → `shift`
- `unshift()` → `unshift`
- `slice()` → `slic()`
- `splice()` → `spli()`

For example:

```js
names.push('mike');
```

## Object Methods

- `Object.keys()` → `keys()`  
- `Object.values()` → `vals()`
- `Object.entries()` → `entr()`

For example:

```js
const keys = Object.keys(user);
```

---


Hope these additional examples help! Let me know if any other common methods come to mind. 

These were just 10 abbreviation techniques you can use to write cleaner JavaScript code! 

_Let me know if you have any other favorites._

> Don't forget to Drop 💖🔥🦄🤯

{% cta https://github.com/taqui-786 %}Follow me in Github✅{% endcta %} 

## Happy coding! 😊