DEV Community

Cover image for 🤓 The Top 10 JavaScript Tricks for Cleaner Code
TAQUI ⭐
TAQUI ⭐

Posted on • Updated on

🤓 The Top 10 JavaScript Tricks for Cleaner Code

Hello Guys, My name is Md Taqui Imam i am a Full Stack developer
And in Today post i will tell you about "The Top 10 JavaScript Tricks for Cleaner Code" that every javascript developers should know.

And i will write a seperate blog as a series on each Trick🔥. So, don't forget to Follow✅

Follow me in Github

Welcome

So Let's Start 🔥

1. 💡 Use Object Destructuring

Object destructuring allows you to extract data from objects into distinct variables. This can make your code cleaner by avoiding repetitively using dot notation.

For example:

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

// Without destructuring
const name = user.name; 
const age = user.age;

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

Pretty cool right? Even a grade schooler can understand this!

2.🧹 Use Default Parameters

Default parameters allow you to set default values for function parameters if none are provided. This avoids repeating yourself by redefining values every time.

For example:

function greet(name = 'Stranger') {
  console.log('Hello ' + name);
}

greet(); // Hello Stranger
greet('John'); // Hello John
Enter fullscreen mode Exit fullscreen mode

Setting default values makes functions more flexible to use.

3.📚 Use Template Literals

Template literals make string concatenation cleaner using backticks and ${expression} instead of plus signs. Even a kid could see this is an easier way to build strings!

For example:

const name = 'John';
const age = 30;

// Without template literals
const greeting = 'Hello ' + name + ', you are ' + age; 

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

Template literals remove lots of pesky concatenation. Neat!

4.✂ Use Array Destructuring

Array destructuring works similarly to object destructuring, allowing you to extract array elements into variables.

For example:

const fruits = ['apples', 'oranges', 'bananas'];

// Without destructuring
const fruit1 = fruits[0];
const fruit2 = fruits[1]; 

// With destructuring
const [fruit1, fruit2] = fruits;
Enter fullscreen mode Exit fullscreen mode

Much simpler! Even a young coder could pick this up.

5.🏃 Use Array Methods

JavaScript has handy array methods to help us write cleaner code. Things like map(), filter(), find(), reduce() etc. can avoid lots of loops and make code more expressive.

For example:

// Filter out all even numbers
const evenNumbers = numbers.filter(num => num % 2 === 0);

// Extract names from objects
const names = users.map(user => user.name); 
Enter fullscreen mode Exit fullscreen mode

JavaScript's array methods are super easy to grasp.

6.🧠 Use Ternary Operator

The ternary operator allows you to write one-line if/else statements in a simpler way.

For example:

// Without ternary
let message;
if(isLoggedIn) {
  message = 'Welcome back!';
} else {
  message = 'Please log in';
}

// With ternary 
const message = isLoggedIn ? 'Welcome back!' : 'Please log in';
Enter fullscreen mode Exit fullscreen mode

Even a young student could pick up this shorthand logic.

7.🛠 Use Object Methods

JavaScript gives objects built-in methods like Object.keys(), Object.values(), JSON.stringify() etc. Using these avoids reimplementing repetitive tasks.

// Get object keys 
const keys = Object.keys(user);

// Convert object to JSON
const json = JSON.stringify(user);
Enter fullscreen mode Exit fullscreen mode

The built-in object methods help keep code tidy and reusable.

8.➕ Use Rest/Spread Properties

The rest/spread syntax allows us to handle function parameters and array elements in flexible ways.

For example:

// Rest parameters
function sum(...numbers) {
  return numbers.reduce((a, b) => a + b);
}

// Spread syntax 
const newArray = [...array, 'new item'];
Enter fullscreen mode Exit fullscreen mode

Even young minds can grasp these concepts that add power to JS.

9.🧸 Use Let & Const

Using let and const avoids unintended behavior from var. They make sure variables are block-scoped and constants can't be reassigned.

For example:

// var is function scoped 
if(true) {
  var snack = 'chips';
}
console.log(snack); // chips 

// let and const are block scoped
if(true) {
  let fruit = 'apples';
  const color = 'red';
}
// fruit not defined here 
Enter fullscreen mode Exit fullscreen mode

Let and const help beginners remember best practices.

💭 In Conclusion

There were just some of the top JavaScript tricks that can help you write cleaner and more elegant code. Even beginning programmers can understand these concepts to get the most out of JavaScript. Keep practicing and have fun with code!

Written By Md Taqui Imam

Happy Coding😊

Top comments (36)

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

A word of warning: Array methods and probably the spread operators do produce clean code. However, you might be paying the price in performance. Why? Because most array methods are JS sugar for loops. If you, say, filter an array and then map it, you'll be running more iterations than if you ran the filterning and mapping at the same time in a for loop of your own.

The other warning would be order of calls. The order matters. If you need to filter and map, try to always filter first, so the map() call iterates over the filtered collection. If done backwards, you'll have wasted cycles.

Collapse
 
artydev profile image
artydev • Edited

Hello,
If performance is a concern look at transducers.
The idea is to apply multiple transformations on an array while iterating it only once.

I am trying to understand them :-)
Here is my very simple implementation

Demo

Collapse
 
taqui_786 profile image
TAQUI ⭐

Absolutely, exploring transducers can optimize array transformations. They apply multiple changes to an array while iterating through it only once, improving performance when efficiency matters.

Your willingness to understand and implement them is commendable. Learning by doing can be a great way to grasp such concepts. Your simple implementation is a valuable start. Keep experimenting and learning. If you have questions or need clarification, don't hesitate to ask. Happy coding! 😊

Thread Thread
 
artydev profile image
artydev

Thank you very for encouraging words :-)

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

OMG do people need a cool word for everything? Just do a loop, and inside said loop, do everything. Don't rely on loop-powered helpers like map(), filter(), reduce(), etc. Do we really need to name this???? What has gone wrong with simplicity? I'll never know.

Thread Thread
 
artydev profile image
artydev • Edited

The for loop is not composable, so it is not applicable for this case
Betwise, transducer is just transformation reducer contraction.
The term reducer is very explicit, it really reduce a collection to a single value.
Naming things is very hard, but it is a nécessity, I am still struggling at it.
Regards

Thread Thread
 
miketalbot profile image
Mike Talbot ⭐ • Edited

The two hardest things in programming: naming things, cache invalidation and off by one errors.

Thread Thread
 
artydev profile image
artydev

Hello Mike,
Thanks again for you great library js-coroutines

Collapse
 
polaroidkidd profile image
Daniel Einars

Oh man, I had totally forgotten about those. I've come across a compose once or twice before. Thanks for reminding me!

Thread Thread
 
taqui_786 profile image
TAQUI ⭐

Hey there,

I appreciate the reminder! Sometimes, we come across techniques and terms, and they slip our minds. Composing functions and using those array methods can indeed clean up the code and make it more readable. It's a good practice to have these tools in our developer toolbox. Thanks for sharing your thoughts! 😊

Collapse
 
syeo66 profile image
Red Ochsenbein (he/him)

Also using an "immutable" style adopted from functional programming leads to the creation of lots of objects and array, and this will cause garbage collection to have to work overtime. This can create some nasty performance issues.

Collapse
 
taqui_786 profile image
TAQUI ⭐

You've raised an important point regarding performance when using an "immutable" style in JavaScript. While these functional programming techniques offer cleaner code, they can have memory and garbage collection implications. Balancing code readability and performance is key, sometimes requiring traditional loops or more efficient methods.

Thanks for highlighting this! 😊

Collapse
 
artydev profile image
artydev • Edited

That is why composition functions are mainly used in functional FP

Collapse
 
taqui_786 profile image
TAQUI ⭐

Hey there,

You bring up a valid point about the performance implications of using array methods and spread operators in JavaScript. It's true that these methods can produce cleaner and more expressive code, but they might not always be the most performant option.

As you mentioned, many array methods are essentially syntactic sugar for loops, and using them in sequence like filtering and then mapping can lead to multiple iterations over the same array. In such cases, using a for loop can be more efficient.

Additionally, the order of method calls is crucial. Filtering before mapping is indeed a good practice because it reduces the dataset that the map function needs to iterate over.

Performance considerations are essential, and it's great that you pointed out these aspects. It's a trade-off between code readability and performance, and developers should be aware of it when making choices.

Thanks for sharing this insight, and it's an essential aspect to keep in mind when writing JavaScript code!

Cheers!😊

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

So I guess everyone is replying comments with ChatGPT.

Thread Thread
 
alvaromontoro profile image
Alvaro Montoro

Isn't it all here? :(

Collapse
 
johannesvollmer profile image
Johannes Vollmer • Edited

While technically correct, this is still bad advice. For beginners and professionala alike, performance should never be a primary concern. The first concern is flexibility, and high-level methods are more flexible than a for loop, especially index based for loops. Being flexible is important for correctness and maintainability, which is both fundamental to achieve before you should begin optimization. What's better: To compute an answer in 5ms, or to be off by one and crash the app in 2ms?

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

I fully disagree. For starters, I never implied that this is the primary concern.
Second, beginners and seasoned professionals alike need to know about performance, and while you should not optimize most of the code from the start, it is such a simple rule to have in mind: "If I need to chain two of these, better do a loop".

This is what happens, in practice:

Junior Dev:

I need to filter and map.

let data = props.data.filter(x => x.isActive).map(y => ({ ...y, visible: true, selected: true }));
Enter fullscreen mode Exit fullscreen mode

Then the project grows more complex and then next junior dev will do, what? Just make the delegates inside filter() and map() more complex. Then the thing grows and grows and nobody is paying attention.

Then new screens come up, and the next junio dev will do, what? You guessed it. It will copy and paste the code of the existing component to create the new one. And now this is spreading in the entire application like wildfire.

Bottomline: It is good advice. Know your language and you'll have an easier time maintaining your application.

Collapse
 
seandinan profile image
Sean Dinan

Very much agree on the order of calls, although multiple calls can often be simplified into a single arr.reduce().

In terms of array methods vs. for loops, you'll often have substantially better performance using map/filter/reduce compared to a for loop. This post does a pretty good comparison of the various approaches.

In the end, I don't think it's too big of a concern unless there's noticeable performance issues happening or there's very large arrays being frequently iterated through.

Collapse
 
lopis profile image
Joao L.

One tip that i sometimes see regarding default parameters: the default parameter is there for when an argument is not provided, or undefined to the function. If the function received another argument such as null, the default parameter naturally won't be used.

Collapse
 
taqui_786 profile image
TAQUI ⭐

Thanks for sharing this insight! 🙌 You're absolutely right about default parameters in JavaScript. Your explanation clears up any potential confusion. It's all about handling the absence of an argument, not just any falsy value. 👍

Collapse
 
budyk profile image
Budy

Great article!!. I think no 8 needs more explanation, like how the function sum is called with the parameter

Collapse
 
taqui_786 profile image
TAQUI ⭐

Thanks for your Kind words, I will write a Separate Blog on each Tricks 😊

Collapse
 
cezarytomczyk profile image
Cezary Tomczyk

Optional chaining (?.) is also nice.

Collapse
 
bias profile image
Tobias Nickel

Nummer sich IS awefull. Over time there are new requirements, and if statements are mich easier to extend. You can put the if statement into a new function if you don't like it in place.

Collapse
 
taqui_786 profile image
TAQUI ⭐

I totally get what you mean! Sometimes, using if statements can make code more flexible and easier to adapt to new requirements over time. And if you ever find them getting too complex, you can always encapsulate them in a separate function for better organization. Keep coding your way! 😊👍

Collapse
 
ant_f_dev profile image
Anthony Fung

Great list!

A bonus of using Object.keys(user); is that you'll only get the properties of user and not its prototype, meaning hasOwnProperty is also no longer necessary.

Collapse
 
taqui_786 profile image
TAQUI ⭐

You bring up a great point about the advantages of using Object.keys(user);. It's not only about code cleanliness but also about avoiding unnecessary properties from the prototype. This indeed makes things much more straightforward and eliminates the need for hasOwnProperty.

Thanks for highlighting this additional benefit! 😊

Collapse
 
iamwillpursell profile image
Will Pursell

Definitely about to go back through my code to make sure I implemented these. Super useful list.

Collapse
 
taqui_786 profile image
TAQUI ⭐

Hey there! It's fantastic that you're planning to go through your code and implement these JavaScript tricks. They are indeed super useful and can make a big difference in writing clean and elegant code. Keep up the great work, and don't hesitate to reach out if you need any help or have questions along the way.

Happy coding! 😊🚀

Collapse
 
pxlmastrxd profile image
Pxlmastr

Great post! I will definitely use these tips soon!

Collapse
 
taqui_786 profile image
TAQUI ⭐

Glad to hear that you find this post helpful.😊

Collapse
 
hasanelsherbiny profile image
Hasan Elsherbiny

nice article.

Collapse
 
taqui_786 profile image
TAQUI ⭐

Glad to hear that you liked it😊

Collapse
 
hasanelsherbiny profile image
Hasan Elsherbiny

nice article

Collapse
 
efpage profile image
Eckehard

I suppose, it is not that simple...