15 Javascript tricks you wish you knew before

Javascript is a very advanced coding langage and its community is one of the largest on the internet, any web developer who’s got a minimal experience should be familiar with Javascript. It is a necessary langage in developing web applications. For most cases, a web developer spends a considerable amount of time coding with javascript when working on a web project. That’s why it’s important for any web developer to improve his js skills as much as he can, because that will definitely impact his productivity. One way to be more efficient in javascript is to be aware of the existence of some tricks that could make your way of coding better, these tricks have always been there, it’s just that few coders are aware of them because they’re uncommon, but if you learn them you’ll notice that you’ll start using them often.

In this article I am going to share with you some of the most useful javascript tricks. These tricks could make your code shorter but don’t forget, sometimes the price is having a code that will be less readable. So keep in mind, not all these tricks are considered “best practice” so you should use them depending on your situation.

1 Shorten an array

Did you know that you can shorten an array by changing its length property?

var a = [1 , 2 , 3]
a.length = 2 // now a is [1 , 2]

2 Convert all elements of an array

You have an array of strings you want to convert into numbers ? you can do it like this:

var strings=['1' , '2' , '3']
numbers = strings.map(Number) // [ 1 , 2 , 3]

This works for Boolean and String as well !

3 Remove duplicates from an array

Sets in javascript are like arrays however they can only contain unique values. You can remove duplicates from an array using this trick :

arr = [ 1 ,2 ,3 ,2 ,3, 4]
arrWithoutDuplicates = [...new Set(arr)] // [1 , 2 , 3 , 4]

4 Assign values to multiple variables at once

You can use destructuring to shorten up how you assign values to variables, see this example:

[a ,b , c] = [1 , 2 ,3] // a=1   b=2  c=3

You can use the same syntax to break down an array into multiple variables

5 Break the array map method loop

Have you ever wanted to be able to break a map loop like when you use the break statement inside a for loop? it is possible to get the array from the parameters of the callback function and mutate it to stop the loop, here’s how

[1 , 2 , 3 , 4].map(function(a,i,arr){
// console output:
// 1
// 2
// 3

this works for reduce, forEach, filter… and any array method that has the array in the parameters of its callback function

6 Increment an array element or initialize it in case it’s null

You can only increment an array element if it already has an initial value otherwise you get an error. This is why you usually need to initialize the element before incrementing it which means you have to write two instructions ( two lines of code ) but this can be done in a single instruction:

var arr = []
arr[0] = ++arr[0] || 1 // arr = [1]

7 Convert a number to binary

using the toString method, you can convert any number to its binary equivalent

Number(3).toString(2) // 11

This works for any base, all you have to do is to change the base number from 2 to any other base

8 The shortest way to sum an array

I don’t suggest using this trick at all because it’s not secure but it’s still worth sharing:

var arr = [1 , 2 , 3]
eval(arr.join("+")) // returns 6

you can replace + with any other arithmetic symbol, for example * will bring you the multiplication of all the array elements

9 Convert an array to a string and vice versa

You can use split and join to convert strings into arrays and arrays into strings:

"abc".split("") // [ "a" , "b" , "c" ]
[ "a" , "b" , "c" ].join("") // "abc"

10 clone an array

Javascript offers many ways to clone an array but using slice is my favorite method

var arr = [1 , 2 , 3]
var arr2 = arr.slice()

11 Dynamic variable name

Variable names can be set dynamically, this can be done like this

var myVarName = "counter"
window[myVarName] = 1 // counter = 1

12 For loop with two variables

We are all used to use the for loop with a single variable, but did you know that you can use more ?

for( var i = 0, j = 5; i<= 5; i++, j-- ){
    console.log("you took "+i+" apples. "+j+" are left")
// you took 0 apples. 5 are left
// you took 1 apples. 4 are left
// you took 2 apples. 3 are left
// you took 3 apples. 2 are left
// you took 4 apples. 1 are left
// you took 5 apples. 0 are left

And you can use as much variables as you like

13 Combine multiple switch cases in a single block

Sometimes you want to call the same code for two or more different switch cases. You don’t have to create two different blocks though. You can combine two or more cases into a single block by cascading the cases statements

       console.log("it feels like summer")

14 Assign the same value to multiple variables in a row

Rather than writing multiple code lines when assigning the same value to multiple variables, you can do it in a single instruction like this:

var a = b = c = "hello"
// a = "hello"
// b = "hello"
// c = "hello"

15 preserve the accuracy of big integers

Long numbers aren’t well supported by javascript, big numbers lose their numeric precision. In most cases, this issue can be dealt with by adding an “n” to the number, by doing so you’re transforming it to a BigInt. Here are some few examples where this can be useful

99999999999999999 // will print 100000000000000000
99999999999999999n // will print 99999999999999999n

1000000000000000000001 // 1e+21
1000000000000000000001n // 1000000000000000000001n

9999999999999998 + 1  // 100000000000000000
9999999999999998n + 1n  // 9999999999999999n

Be careful though, BigInt isn’t like regular numeric type. Even if you can perform arithmetic operations like addition or multiplication, there are some exception you should be aware of before using them in production. I highly suggest you read about the BigInt Object and how it affects the traditional arithmetic operations.

Also read...

Leave a Reply

Your email address will not be published. Required fields are marked *