DEV Community

Navin Mishra
Navin Mishra

Posted on • Updated on

8 Javascript useful techniques

js cover

This article collects some common javascript techniques for clean code and better development efficiency

1. Converting string to number.

We might be using Number() and parseInt() to convert string to number. But we can use "+" as well:

Example:

const str = '123';
const num = +str
Enter fullscreen mode Exit fullscreen mode

2. Converting number to string

There is another method to convert number to string.

Example:

const num = 123;
const str = ""+num
Enter fullscreen mode Exit fullscreen mode

But considering readibility and performance, String() and template string are recommended.

3. Ternary operator

The ternary operator is a shorthand way of writing an if-else statement in JavaScript. It is represented by the ? and : symbols, and has the following syntax:

condition ? expression1 : expression2
Enter fullscreen mode Exit fullscreen mode

Example using if/else statement:

let num = 5;
let message;

if (num > 0) {
  message = "Positive";
} else {
  message = "Non-positive";
}
console.log(message); // Output: "Positive"
Enter fullscreen mode Exit fullscreen mode

The same code can be written using the ternary operator as follows:

let num = 5;
let message = (num > 0) ? "Positive" : "Non-positive";
console.log(message); // Output: "Positive"
Enter fullscreen mode Exit fullscreen mode

4. Use object instead of "switch"

We often use switch to handle different things, but have you ever thought of using an object to greatly simplify your code? Let me explain in code.

const n = 1
let result;
switch (n) {
  case 1:
    result = 'res-1'
    break
  case 2:
    result = 'res-2'
    break
  case 3:
    result = 'res-3'
    break  
  // ...There are a lot more
}
Enter fullscreen mode Exit fullscreen mode

We only need to use object map to achieve our goal:

const n = 1
const nMap = {
  1: 'res-1',
  2: 'res-2',
  3: 'res-3'
}
const result = nMap[ n ]
Enter fullscreen mode Exit fullscreen mode

5. Use the "includes" method instead of multiple "if"

We often writes code like this but multiple conditions makes the logic more confusing.

Example:

const n = 1
if (n === 1 || n === 2 || n === 3 || n === 4 || n === 5) {
  // ...
}
Enter fullscreen mode Exit fullscreen mode

Let's use "includes" method to make our code extra clean and maintainable:

const n = 1
const conditions = [ 1, 2, 3, 4, 5 ] // You just need to add new numbers here
if (conditions.includes(n)) {
  // ...
}
Enter fullscreen mode Exit fullscreen mode

6. Use the default parameters of the ES6 function

Example:

const func = (name) => {
  name = name || 'magic'
  console.log(name)
}
Enter fullscreen mode Exit fullscreen mode

Let's use like this instead:

const func = (name = 'magic') => {
  console.log(name)
}
Enter fullscreen mode Exit fullscreen mode

7. Improve variable logging using console.log

Instead of using like this:

const str = "magic"
console.log("str:", str);
Enter fullscreen mode Exit fullscreen mode

We can use like this to improve readability.

const str = "magic"
console.log({str});
Enter fullscreen mode Exit fullscreen mode
This will print like an object with key as "str" and value as "magic".

8. Use of nullish coalescing operator with numbers

The Nullish Coalescing Operator (??) is a logical operator that accepts two values and returns the second value if the first one is null or undefined and otherwise returns the first value.

Example:

let num = 0;
let num2;

console.log(num || 1); // 1
console.log(num2 || 2); // 1
Enter fullscreen mode Exit fullscreen mode

Let's use '??' operator now.

let num = 0;
let num2;

console.log(num ?? 1); // 0
console.log(num2 ?? 2); // 2
Enter fullscreen mode Exit fullscreen mode

Hope you find these techniques useful and able to make your code cleaner. Happy reading!!

Top comments (14)

Collapse
 
damian_cyrus profile image
Damian Cyrus

One interesting point in these cases of usefull techniques are two things:

  • is it understandable (also looking at the type of the variable)?
  • how is the performance in combination with readability and maintance?

Points to the first example:

There are good reasons why we use String() or .toString(). In these cases it is clear that the variable is changing its type. This is not so clear in ""+num.

From a reading point of view you are mixing two types, but you are not transforming it. In the end the JavaScript engine decides for you what it should become, and not you.

It also does not help others to figure out what that shortcut really does and could ask why you add an empty string to a number (if you read it literary) just to transform a number rather use optimised functions for transformation. I would like to ignore template literals in this case, as they have another use case.

What about performance?

You could also look up some benchmarks: measurethat.net/Benchmarks/Show/24...

There are even more benchmarks for this kind of tricks.

I don't say you should always use the best thing for performance, but using some weirdness of a language just because you can might hurt the readability and in the end maintainability.

Else, a nice read. Thanks and keep going 😃

Collapse
 
navinmishra1717 profile image
Navin Mishra • Edited

Hi damian, thanks for the comment and putting the point on readability and performance. I have only pointed out some useful techniques which means we can also use them if we like to use. Im not saying it is best for performance. Infact, i mostly use String() and template string in my codes as well. Thanks again!!

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Readability is completely subjective, and preaching it above all else can damage the quality of developers over time - sweeping features or 'weirdness' of a language under the carpet will only result in a diminishing understanding of that language and the various 'tricks' (for performance, brevity etc.) that are available.

Learn everything you can about a language and make your own decisions about what features are best to use in each situation. Don't bow to dogma.

Collapse
 
navinmishra1717 profile image
Navin Mishra

Agreed. Thanks for the comment Jon!!

Collapse
 
ant_f_dev profile image
Anthony Fung

To convert numbers to strings, you can also use string templates:

const num = `${123}`;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
leocifer profile image
Lionel Dsilva

This is a far more readable way to do it

Collapse
 
navinmishra1717 profile image
Navin Mishra

There are few other methods as well. But template string is the one i mostly use as well. Thanks for reading!!

Collapse
 
exconf profile image
Sergiy

In the second example shouldn't the names be like this?

const num = 123;
const str = ""+num

Collapse
 
navinmishra1717 profile image
Navin Mishra

My bad.It should be like this, i'll update. Thanks!!

Collapse
 
corners2wall profile image
Corners 2 Wall • Edited

In my opinion, first and second points looks so dirty

Collapse
 
navinmishra1717 profile image
Navin Mishra

Might be, but these are only useful Techniques. So we need to use as per our case. Thanks for reading!!

Collapse
 
nikeshdahal profile image
Nikesh Dahal

useful

Collapse
 
navinmishra1717 profile image
Navin Mishra

Thanks nikesh. I hope you liked it. Happy reading!!

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Only 1 (I think) item here has anything to do with ES6