Increase productivity as a Developer by knowing these JavaScript Hacks

Increase productivity as a Developer by knowing these JavaScript Hacks

Table of contents

No heading

No headings in the article.

There are many amazing features in javascript that can make your life much simpler.

I have added some of the amazing features that every javascript developer should know.

1. Resize the Array using an array. length.

a=['Pune','Hyderabad','Banglore','Mumbai','Indore','Delhi']
console.log(a.length) //OUTPUT 6
a.length=3
console.log(a) //OUTPUT ['Pune','Hyderabad','Banglore']

2. Use Filter in a different way.

a=[null,undefined,{"name":"Alex"},{"name":"Nick"},{"name":""},null]
c=a.filter(item=>item.name.length>0) //this will show error Uncaught TypeError: Cannot read property 'length' of undefined

// we can use filter with Boolean to remove null and undefined Values

c=a.filter(Boolean).filter(it=>it.name.length>0) //This will work
console.log(c) //OUTPUT

3. Concatenating two or more arrays without causing server overload.

//old way
a=[1,2,3,4,5]
b=[4,5,6,7,8]
c=a.concat(b) //This will Create a new array c and then will push contents fo array a and array b in array c which will consume lot of memory.
console.log(c) //OUTPUT:1,2,3,4,5,4,5,6,7,8


//new way
a=[1,2,3,4,5]
b=[4,5,6,7,8]
a.push.apply(a,b) // it will only push the content of array b in array a.
console.log(a)

4. Replace all occurrences of a word in a string

str="India India USA India UK India"
console.log(str.replace(/India/,'USA'))
//OUPUT USA India USA India UK India
//Add g at the end of string it will replace all occurences
console.log(str.replace(/India/g,'USA'))

5. Shortcut for conditions.

Here, I am explaining two examples, we can implement in multiple ways.

// old way
let a="hello"
let b;
if(a==undefined)
{
b="Nothing"
}
else
{
b=a
}
console.log(b) //hello

//new way
b=a||"Nothing"
console.log(b) //hello

// old way
let data={"name":"Allen"}
if(data!=undefined)console.log(data.name)

// new way
data!=undefined&&console.log(data.name)

6. Use console.table

// we can use console.table to show objects in tabular format
a=[{"city":"Banglore"},{"city":"Pune"},{"city":"Mumbai"}]
console.table(a)

7. Call a function by its name stored in a string using eval function.

const print=()=>console.log("hello")
setTimeout(()=>eval('print')(),1000)//hello

Thanks for reading. I will explain more such amazing features in my next blog.

Happy Learning!!