20 JavaScript Hacks You don't know!

Every web dev uses JavaScript in his projects. So here are some cool js hacks and features you might not know to make you code less and be more pro...

Did you know?

NaN in JavaScript stands for Not-a-Number and it is used to indicate if a value is a legal number

Hello, are you a web developer? 

If yes, then you must be using JavaScript very much for your projects. So this post is for you. 

In this post I am going to make you aware of 20 great JavaScript hacks or features you don’t know! Using this hacks will make your coding life much easier and you don’t have to write more code and logics while making a project. 

Then lets dive in...

JavaScript Hacks You don't know
  1. Swapping two Numbers
    let a=3;
    let b=4;
    console.log(a,b) //OUTPUT: 3, 4
    console.log(a,b) //OUTPUT :4, 3

    Swapping means interchanging values. In the above code we assigned the values 3 and 4 to the variables a and b respectively. Then to swap their values we used a simple method here other than using a third variable.

  2. Resize an array using array.length
    arr =['Python','JavaScript','Csharp','Java','Kotlin','Cpp','C']
    console.log(arr.length) //OUTPUT 7
    console.log(a) //OUTPUT ['Python','JavaScript','Csharp']

    In this method the array can be resized easily without rewriting or removing the elements manually. the arr.length assigns the new lenth to the array and then other elements are automatically removed.

  3. Iterating on a map from 0 to n.

    Iteration can be done in a easy way as above without using a long coded loop. Just one line of code to iterate through a map from 0 to n easily. and then the console.log method logs the output to console.

  4. Using filter in a different Way
    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

    Filter can be used to remove null values so the error as written in the code can be solved using the filter method at the 6th line.

  5. Concatenating two or more arrays
    //old way
    c=a.concat(b) //This will Create a new array c and then will push contents of 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.push.apply(a,b) // it will only push the content of array b in array a.

    While concatenating two arrays in the old times we were creating a new array and then use it to concatenate the 2 arrays. Which consumes a lot of memory. But now we using the push method the contents of one array can be pushed to another. Which results in use of less memory because no new array is created like the old method.

  6. Replace all occurrences of a word in a string
    str="India India USA India UK India"
    //OUPUT USA India USA India UK India
    //Add g at the end of string it will replace all occurences

    Above method can be used while replacing a word in an array easily.

  7. Shortcut for conditions
    // old way
    let a="hello"
    let b;
    console.log(b) //hello
    //new way
    console.log(b) //hello
    // old way
    let data={"name":"Allen"}
    // new way

    Above two ways can be used to make conditional codes smaller and save your time.

  8. String to Number or Number to String Conversion

    The following method can be used to convert a String to Number or vice-versa in a simpler way.

    // string to number
    console.log(+a) //Output 123
    console.log(+b) //NaN
    //number to string
  9. Using the console in a different way
    // %s replaces an element with a string
    console.log("Helllo I love %s","Javascript")
    // %d  replaces an element with an integer
    console.log("Helllo %d ",1)
    // %f  replaces an element with a float
    console.log("Helllo  %f ",1.078)
    // %(o|O) | element is displayed as an object.
    console.log("Helllo %O",{"Name":"Sidd"})
    // %c | Applies the provided CSS
    console.log("%cThis is a red text", "color:red");
  10. The console.table method
    // we can use console.table to show objects in tabular format

    The output will show a table like in this image

  11. Get n power of any number
    console.log(2 ** 3) //8
    console.log(2 ** 12)  //4096

    Generally, Everyone knows the above method but some begginers don't. So instead of using a loop we can use two astericks to find n power of a number.

  12. Check the false or true value
    //In javascript following values are false 0, "", null, undefined, NaN and of course false except it all are true
    // use !! operator to get false or true
    console.log(!!0,!! "",!!null,!! "Hii",!! undefined,!! NaN ,!! false,!! true)
    //OUTPUT false false false true false false false true
  13. typeof Operator
    //The typeof operator returns a string indicating the type of the unevaluated operand.
    console.log(typeof 12) //number
    console.log(typeof "hello") //string
    console.log(typeof []) //object
    console.log(typeof true) //boolean
    console.log(typeof {}) //object
  14. Get the items near to last index of an array
  15. Call a function by its name stored in a string using eval function
    >const print=()=>console.log("hello")
  16. The label statement
    //The labeled statement can be used with break or continue statements. It is prefixing a statement with an identifier which you can refer to.
    for (let i = 0; i < 5; i++) {
      for(let j=0;j<5;j++)
          continue loop1
    // 0 0
    // 1 0
    // 1 1
    // 2 0
    // 2 1
    // 2 2
    // 3 0
    // 3 1
    // 3 2
    // 3 3
    // 4 0
    // 4 1
    // 4 2
    // 4 3
    // 4 4
  17. Rest parameters Syntax
    //The rest parameter syntax allows a function to accept an indefinite number of arguments as an array,it like variadic function in C.
    function abc(...args)
    abc(1) //[1]
    abc(1,2) //[1,2]
    abc(1,2,3) //[1,2,3]
  18. new.target in javascript
    // new.target is used to detect that weather a function or constructor call using new or not.
    // if it called using new it will return refrence to constructor or function else it return undefined.
    function learn(){ 
      new.target?console.log("Called using new"):console.log("Called without new")
    learn() //called without learn
    new learn() //called using new.
    //In arrow functions, new.target is inherited from the surrounding scope.
  19. function* in javascript
    //The function* declaration (function keyword followed by an asterisk) defines a generator function, which returns a Generator object.
    function* generator(i) {
      yield i;
      yield i + 10;
    const gen = generator(10);
    // expected output: 10
    // expected output: 20
  20. yield keyword
    //The yield keyword is used to pause and resume a generator function 
    function* list(index,length) {
      while (index < length) {
        yield index;
    const iterator = list(0,10);
    // expected output: 0
    // expected output: 1

Thanks for reading!
Keep visiting devtejas.me for more tricks and tips related to computer science.