5 Useful JavaScript Tips & Tricks For Writing Clean and Short Code

5 Useful JavaScript Tips & Tricks For Writing Clean and Short Code

ยท

2 min read

Hey guys ๐Ÿ‘‹, As we know Javascript gaining more and more popularity every day. There are some tips and tricks which will make you a better developer and also help you write clean, short, and concise code.

While reading a Javascript book, I compile some tricks that will make a better impact on your development process. Without further delay let's start discussing it.

1. Convert to number:

Usually, when we convert string to a number, then we write code explicitly to convert String to number:

let str = '12';
let str_to_Number = Number(str);
console.log(typeof(str_to_Number);  //Type: Number

But now, there is a shorter way to convert strings to numbers explicitly with + operator:

let str = '12';
let str_to_Number = +str;
console.log(typeof(str_to_Number); //Type: Number

2. Merge Arrays in Javascript:

If we have two or more arrays then we can merge it easily with ... operator:

const arr_1 = [1, 2, 3, 4];
const arr_2 = [5, 6, 7, 8];
const merge_arr = (...arr_1, ...arr_2)
console.log(merge_arr); //1, 2, 3, 4, 5, 6, 7, 8

3. For Loop in a shorter way:

We know how a normal for-loop works:

const student = ["Ahmad", "Smith", "Krish"];

for (let i = 0; i < student.length; i++) {
  const student_name = student[i];
  console.log(student_name);
}

But instead of a normal for-loop now when can use a for-of loop to shorter it.

const student = ["Ahmad", "Smith", "Krish"];

for (let student_name of student) console.log(student_name);

4. Convert Number to String:

Usually, we use toString( ) in order to convert a number into a string, Let's see:

let num = 123;
let str_num = num.toString();
console.log(typeof(str_num)); //string

But, there is a small trick that helps you to convert numbers to strings quickly. By concatenation a number with an empty string. let's see the example:

let num = 123 + "";
console.log(num); //  "123"
console.log(typeof(num)); //string

5. Convert to Boolean:

We can easily convert any value to Boolean by using !! operator:

console.log(!!0); // Output: false
console.log(!!1); // Output: true
console.log(!!""); // Output: false
console.log(!!" "); // Output: true

Conclusion:

I hope that you found these tips as useful as I did and used them on daily basis. Do you know of any cool and useful JavaScript tricks? Iโ€™d love to read them in the comments!

If you got any questions or doubts, feel free to ping me on Twitter

I hope it was a great read for you. If you have any feedback please share it in the comment below.

ย