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
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;
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];
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?`;
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;
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;
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';
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);
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);
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;
π Bonus π
11. DOM Manipulation abbreviations methods β
-
addEventListener
βaddEvent
-
removeEventListener
βremoveEvent
-
getElementById
βgetElem
-
getElementsByTagName
βgetElems
-
classList
βclass
For example:
getElem('btn').addEvent('click', handleClick);
String Methods
-
toUpperCase
βtoUpper
-
toLowerCase
βtoLower
-
includes()
βincl()
-
indexOf()
βindOf()
-
substring()
βsubstr()
-
split()
βspli()
For example:
let name = 'johnDoe'.toLower();
Array Methods
-
push()
βpush
-
pop()
βpop
-
shift()
βshift
-
unshift()
βunshift
-
slice()
βslic()
-
splice()
βspli()
For example:
names.push('mike');
Object Methods
-
Object.keys()
βkeys()
-
Object.values()
βvals()
-
Object.entries()
βentr()
For example:
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 ππ₯π¦π€―
Top comments (3)
So you just keep making things up? I have no idea how you got the idea abbreviations like
toUpper
orgetElem
even exist.substring
andsubstr
do both exist (howeversubstr
is deprecated) but are certainly not the same.Also
Why not simply use
?
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:
You're absolutely right, it can be simplified to:
Simplifying code like this not only makes it more concise but also easier to read and maintain. Thanks for sharing your insights! ππ
"some of the abbreviations mentioned may not be standard or widely used"
No, they simply do not exist.