DEV Community

Cover image for 10 JavaScript Shorthand Techniques To Improve Efficiency πŸ’‘
TAQUI ⭐
TAQUI ⭐

Posted on

10 JavaScript Shorthand Techniques To Improve Efficiency πŸ’‘

Welcome

Hi friends! πŸ‘‹ its me Md Taqui Imam, welcome to my new blog.

Today I want to share ✨10 cool ways to shorten your JavaScript code 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!

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

2. Object Destructuring πŸ“¦

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

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

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

// With destructuring
const { name, age } = user;
Enter fullscreen mode Exit fullscreen mode

So much shorter!

3. Spread Syntax ...

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

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

// With spread
const combined = [...arr1, ...arr2];
Enter fullscreen mode Exit fullscreen mode

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:

const name = 'John';

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

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

No more concatenation!

5. Arrow Functions =>

Arrow functions provide a shorter syntax for writing function expressions.

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

// Arrow function  
const sum = (a, b) => a + b;
Enter fullscreen mode Exit fullscreen mode

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.

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

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.

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

// With nullish coalescing
const name = user.name ?? 'Guest';
Enter fullscreen mode Exit fullscreen mode

8. Logical Operators && and ||

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

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

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.

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

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

10. Ternary Operator ? :

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

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

// With ternary operator
const accessAllowed = age > 18 ? true : false;
Enter fullscreen mode Exit fullscreen mode

πŸŽ‰ Bonus πŸŽ‰

11. DOM Manipulation abbreviations methods ⭐

  • addEventListener β†’ addEvent
  • removeEventListener β†’ removeEvent
  • getElementById β†’ getElem
  • getElementsByTagName β†’ getElems
  • classList β†’ class

For example:

getElem('btn').addEvent('click', handleClick);
Enter fullscreen mode Exit fullscreen mode

String Methods

  • toUpperCase β†’ toUpper
  • toLowerCase β†’ toLower
  • includes() β†’ incl()
  • indexOf() β†’ indOf()
  • substring() β†’ substr()
  • split() β†’ spli()

For example:

let name = 'johnDoe'.toLower();
Enter fullscreen mode Exit fullscreen mode

Array Methods

  • push() β†’ push
  • pop() β†’ pop
  • shift() β†’ shift
  • unshift() β†’ unshift
  • slice() β†’ slic()
  • splice() β†’ spli()

For example:

names.push('mike');
Enter fullscreen mode Exit fullscreen mode

Object Methods

  • Object.keys() β†’ keys()
  • Object.values() β†’ vals()
  • Object.entries() β†’ entr()

For example:

const keys = Object.keys(user);
Enter fullscreen mode Exit fullscreen mode

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 πŸ’–πŸ”₯πŸ¦„πŸ€―

Follow me in Githubβœ…

Happy coding! 😊

Top comments (3)

Collapse
 
syeo66 profile image
Red Ochsenbein (he/him) • Edited

So you just keep making things up? I have no idea how you got the idea abbreviations like toUpper or getElem even exist. substring and substr do both exist (however substr is deprecated) but are certainly not the same.

Also

const accessAllowed = age > 18 ? true : false;
Enter fullscreen mode Exit fullscreen mode

Why not simply use

const accessAllowed = age > 18;
Enter fullscreen mode Exit fullscreen mode

?

Collapse
 
taqui_786 profile image
TAQUI ⭐

You bring up some valid points, and I appreciate the clarification. Indeed, JavaScript has its own set of techniques and best practices, and some of the abbreviations mentioned may not be standard or widely used. As for the example:

const accessAllowed = age > 18 ? true : false;
Enter fullscreen mode Exit fullscreen mode

You're absolutely right, it can be simplified to:

const accessAllowed = age > 18;
Enter fullscreen mode Exit fullscreen mode

Simplifying code like this not only makes it more concise but also easier to read and maintain. Thanks for sharing your insights! πŸš€πŸ‘

Collapse
 
syeo66 profile image
Red Ochsenbein (he/him)

"some of the abbreviations mentioned may not be standard or widely used"
No, they simply do not exist.