Do you know these JS Hacks | Tricks

·

3 min read

While developing application I feel that these are some hacks which we can add in our code to make it little smart with less number of…


Do you know these JS Hacks | Tricks

[ES6 & ES7 Tips and Tricks || Hacks in Javascript
_Hack with Javascript Array_medium.com](https://medium.com/tkssharma/es6-es7-tips-and-tricks-hacks-in-javascript-d7dc03cd1b71 "medium.com/tkssharma/es6-es7-tips-and-trick..")

[Immutability in Javascript | Array and Objects
_In object-oriented and functional programming, an immutable object (unchangeable object) is an object whose state…_medium.com](https://medium.com/tkssharma/immutability-in-javascript-array-and-objects-a593e3479e8e "medium.com/tkssharma/immutability-in-javasc..")

While developing application I feel that these are some hacks which we can add in our code to make it little smart with less number of lines — some of these you might be using already

  • Use Promise Object. finally ()

When you use the somePromise.then(x).catch(y).finally(z) pattern, your business logic is generally happening in the then callback (x, above - what you want to do once somePromise has resolved) or in the catch callback (y above - returns what you want to pass along in case something goes horribly wrong). You might never have even used finally in your code - and that's fine.

According to the MDN docs, a finally callback allows you to execute logic once your Promise has been settled - resolved or rejected - one way or the other.

p.finally(onFinally);  

p.finally(function() {  
  // settled (fulfilled or rejected)  
   // reset loading state   
   // reset object or application state   
});
  • Using Destructuring with Array.prototype Methods()
const arr = [{ name : 'tks'}, {name : 'kumar'}]  

arr.map( ({name}, index) => {  
console.log(name, index);  
return name;  
})
const arr = [{ name : 'tks'}, {name : 'kumar'}]  
arr.filter( ({name}, index) => {  
   return true;    
})
  • Removing a Property from Object using … operator
const obj = {a :10, b:40, c:70}  
const {a,...finalObj} = obj;
  • Deep Copy of Object (can we write Code for this ? )
const obj = {a :10, b:40, c:70}

object.assign -- Shallow Copy (not capable for deep copy of nested properties)
JSON.parse and stringify just a workaround to create deep copy
The spread syntax and Object.assign() allow us to make only
shallow copies of objects in JavaScript. Deeply nested values are // in fact put there just as a reference to the source object. return Promise.resolve and Promise.reject instead of creating new Promise(cbk)

function getData(){  
return new Promise((resolve,reject) => {   
 return axios.get('').then(data => {  
      resolve(null)})  
 }) // else reject   
}
function getData(){  
return axios.get().then(data => Promise.resolve(data))  
}// else reject   
// Both functions are returning promise Object
  • Become fully obsessed with destructuring {}
function getAvengers() {  
  return ['Ironman', 'Captain America', 'Thor', 'Hulk']  
}  
const [ a, , , b ] = getAvengers();  
// Notice that I created two commas in the middle. This means that I'm skipping both Captain America and Thor  
console.log(a); // 'Ironman'  
console.log(b); // 'Hulk'

function CategoryBanner({ category }) {}  
function CategoryBanner({ data, id, ...rest }) {}
  • update object property using {…} better option then Object.assign
const obj = {x :80};  
const anotherObj = {c :80}  
const newObj  = {...obj, x:700, y:600, ...anotherObj}  
// works same as Object.assign // sort and simple   
const veryNewObj = {  
...newObj,  
X:90  
}
  • Destructuring with spread operator, get what you need rest put in …rest
function CategoryBanner({ data, id, ...rest }) {  
   console.log(data,id,rest)  
// rest will be {x:80, y :70}  
}
const newobj = {data : [], id :80, x:80, y:70}  
CategoryBanner(newobj)
  • Using length to delete/ empty in an array
const array = [1,,3,4,56,7,8];  
array.length =  2;  
// Now array will have only two values rest all will be vanished ..
  • values using || operator to get rid of null value errors
const data = somemethod(data) || [];  
const env = process.env.NODE_ENV || 'DEV'
  • Strict null checks
if(!data || !Array.isArray(data.list) || data.list.length === 0){  
   console.log('array is null or data is null')  
}

const data = {x :80}

if(data &&  data.x) {console.log('yes i do have value x in data')}