8 JavaScript Tips & Tricks That No One Teaches 🚀
Garvit Motwani

Garvit Motwani @garvitmotwani

About: Web Developer 👨‍🎓 13 👨‍💻 HTML, CSS, JavaScript, ReactJS

Location:
Indore, India
Joined:
Apr 20, 2020

8 JavaScript Tips & Tricks That No One Teaches 🚀

Publish Date: Apr 6 '21
737 81

JavaScript is no doubt one of the coolest languages in the world and is gaining more and more popularity day by day. So the developer community has found some tricks and tips after using JS for quite a while now. Today I will share 8 Tips & Tricks With You!

So let's get started

Functional Inheritance

Functional inheritance is the process of receiving features by applying an augmenting function to an object instance. The function supplies a closure scope which you can use to keep some data private. The augmenting function uses dynamic object extension to extend the object instance with new properties and methods.

They look like:

// Base function
function Drinks(data) {
  var that = {}; // Create an empty object
  that.name = data.name; // Add it a "name" property
  return that; // Return the object
};

// Fuction which inherits from the base function
function Coffee(data) {
  // Create the Drinks object
  var that = Drinks(data);
  // Extend base object
  that.giveName = function() {
    return 'This is ' + that.name;
  };
  return that;
};

// Usage
var firstCoffee = Coffee({ name: 'Cappuccino' });
console.log(firstCoffee.giveName());
// Output: "This is Cappuccino"
Enter fullscreen mode Exit fullscreen mode

Credits to @loverajoel for explaining this topic in depth here - Functional Inheritance on JS Tips which I've paraphrased above

.map() Substitute

.map() also has a substitute that we can use which is .from():

let dogs = [
    { name: Rio, age: 2 },
    { name: Mac, age: 3 },
    { name: Bruno, age: 5 },
    { name: Jucas, age: 10 },
    { name: Furr, age: 8 },
    { name: Blu, age: 7 },
]


let dogsNames = Array.from(dogs, ({name}) => name);
console.log(dogsNames); // returns [“Rio”, “Mac”, “Bruno”, “Jucas”, “Furr”, “Blu”]
Enter fullscreen mode Exit fullscreen mode

Number to string/string to number

Usually, to convert a string to a number, we use something like this:

let num = 4
let newNum = num.toString();
Enter fullscreen mode Exit fullscreen mode

and to convert a string to a number, we use:

let num = "4"
let stringNumber = Number(num);
Enter fullscreen mode Exit fullscreen mode

but what we can use to code fast is:

let num = 15;
let numString = num + ""; // number to string
let stringNum = +s; // string to number
Enter fullscreen mode Exit fullscreen mode

Using length to resize and emptying an array

In javascript, we can override a built-in method called length and assign it a value of our choice.

Let's look at an example:

let array_values = [1, 2, 3, 4, 5, 6, 7, 8];  
console.log(array_values.length); 
// 8  
array_values.length = 5;  
console.log(array_values.length); 
// 5  
console.log(array_values); 
// [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

It can also be used in emptying an array, like this:

let array_values = [1, 2, 3, 4, 5, 6, 7,8]; 
console.log(array_values.length); 
// 8  
array_values.length = 0;   
console.log(array_values.length); 
// 0 
console.log(array_values); 
// []
Enter fullscreen mode Exit fullscreen mode

Swap Values with Array Destructuring.

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. We can also use that to swap values fast, like this:

let a = 1, b = 2
[a, b] = [b, a]
console.log(a) // result -> 2
console.log(b) // result -> 1
Enter fullscreen mode Exit fullscreen mode

Remove duplicates from an Array

This trick is pretty simple. Let's say, I made an array that is containing numbers, strings, and booleans, but the values are repeating themselves more than once and I want to remove the duplicates. So what I can do is:

const array = [1, 3, 2, 3, 2, 1, true, false, true, 'Kio', 2, 3];
const filteredArray = [...new Set(array)];
console.log(filteredArray) // [1, 3, 2, true, false, "Kio"]
Enter fullscreen mode Exit fullscreen mode

Short For Loop

You can write less code for a loop like this:

const names = ["Kio", "Rio", "Mac"];

// Long Version
for (let i = 0; i < names.length; i++) {
  const name = names[i];
  console.log(name);
}

// Short Version
for (let name of names) console.log(name);
Enter fullscreen mode Exit fullscreen mode

Performance

In JS you can also get the time that the code was executed in like Google does:

google example

It looks like this:

const firstTime = performance.now();
something();
const secondTime = performance.now();
console.log(`The something function took ${secondTime - firstTime} milliseconds.`);
Enter fullscreen mode Exit fullscreen mode

⚡️ Giveaway ⚡️

We are giving away any course you need on Udemy. Any price any course.
Steps to enter the giveaway
--> React to this post
--> Subscribe to our Newsletter <-- Very important
--> Follow me on Twitter <-- x2 Chances of winning

The winner will be announced on May 1, Via Twitter


Thank you very much for reading this article.

Comment any tricks & tips you know!

PLEASE LIKE, SHARE, AND COMMENT

Follow me on Dev and Twitter

Comments 81 total

  • АнонимApr 6, 2021

    [hidden by post author]

    • Garvit Motwani
      Garvit MotwaniApr 6, 2021

      Ya sorry actually I wrote it before because I wanted to create a CSS post 😅 thanks for the reminder

  • buridev
    buridevApr 6, 2021

    awesome bro, thanks for sharing

  • АнонимApr 6, 2021

    [hidden by post author]

  • Jimmy
    JimmyApr 6, 2021

    Really nice tips.
    Question : what is the best option between using performance.now() and console.time() 🤔

    • Garvit Motwani
      Garvit MotwaniApr 7, 2021

      I usually use performance.now() so I would recommend that but console.time() is also good!!

    • J. G. Sebring
      J. G. SebringApr 8, 2021

      console.time will be limited to output in console, hence it is more suitable for temporary debugging/test situations.

      Any other cases I'd use performance.now, like displaying time in html, sending to backend etc.

      • Jimmy
        JimmyApr 8, 2021

        Good to know thanks for this tip 😀👍

  • АнонимApr 6, 2021

    [hidden by post author]

    • Garvit Motwani
      Garvit MotwaniApr 7, 2021

      Actually, I really like that method and it is way easier than .map(), that's why I recommended that, but noted! Thanks for reading the article

      • Nick Morton
        Nick MortonApr 7, 2021

        Please explain how your method is "way easier than .map()"?

        I just don't understand your thinking here, the concepts are exactly the same, the syntax is almost exactly the same (actually longer), and you're introducing a somewhat unfamiliar syntax to most to achieve something that everyone likely understands already with .map().

  • Vicky Vasilopoulou
    Vicky VasilopoulouApr 6, 2021

    thanks for sharing Garvit!

  • Muhammad Talha Akbar
    Muhammad Talha AkbarApr 6, 2021

    Great, Garvit! It's always great to know the language so well and bring about these unconventional ways to solve problems. However, it's always recommended to write code that is self-explanatory. And, I find majority of these tricks to be confusing (to an average eye). Use them when you really have to and leave a comment to make your intention clear.

    • Garvit Motwani
      Garvit MotwaniApr 7, 2021

      Noted! and thanks for reading the article!

    • Strat Barrett
      Strat BarrettApr 8, 2021

      On that note – which I completely agree with – it's interesting how readable this is Array.from(dogs) compared to dogs.map() if map wasn't so widely adopted :)

      • An actual, Real Samurai
        An actual, Real SamuraiApr 12, 2021

        On that note, I'd love to see how performant Array.from() is compared to .map() that I know doesn't perform very well

        • Michael R.
          Michael R.Apr 13, 2021

          Now you've inspired a more ambitious project. Building a custom standalone performance measurement tool for Javascript.

          It could be something similar to Runkit, but strictly for benchmarking the various methods and approaches to the same end goal. Like which is faster?

          capsLockNames = names.map(capitalize)
          
          Enter fullscreen mode Exit fullscreen mode

          OR

          capsLockNames= []
          for x = 0; x < names.length; x++
            capsLockNames[x] = capitalize(names[x]))
          
          Enter fullscreen mode Exit fullscreen mode

          🤔🤔🤔

          • An actual, Real Samurai
            An actual, Real SamuraiApr 14, 2021

            I can tell you for sure that the for loop is way more performant than map. But if you do compare everything, I'm definitely interested to read.

  • Bret
    BretApr 6, 2021

    The problem with JavaScript is that.... it’s not taught “in context”, it’s mainly always a “console.log” that is used for the answer, instead of truly implementing it into real examples.... it’s been tough for me to learn it

    • Garvit Motwani
      Garvit MotwaniApr 7, 2021

      Ya

    • Vicropht
      VicrophtApr 12, 2021

      Make projects to learn it! Helps a lot!!!

    • Michael R.
      Michael R.Apr 13, 2021

      Liquid syntax error: Tag '{%' was not properly terminated with regexp: /\%\}/

  • АнонимApr 7, 2021

    [hidden by post author]

  • Jason F
    Jason F Apr 7, 2021

    Great article. I'm particularly fond of the map without map.

  • tryhendri
    tryhendriApr 7, 2021

    Thanks for sharing Garvit
    It seems a typo on Map an array without .map(), it should return dogsNames rather than friendsNames.

  • Yavor Chanov
    Yavor ChanovApr 7, 2021

    Hi, thanks for the article.
    I think there is a small mistake in the "Number to string/string to number" part...
    The example for converting string to number is:
    let num = "4"
    let stringNumber = Number(s); //doesn't that have to be Number(num);?

  • Abdallah Daiyan
    Abdallah DaiyanApr 7, 2021

    For me remove duplicates in an array was interesting.....past I removed in another way. It seems like this is so easy....Thank you so much man...It was awesome 🚀🔥

  • Brad Mehder
    Brad MehderApr 7, 2021

    I found this article super useful!

  • Garvit Motwani
    Garvit MotwaniApr 7, 2021

    It varies from person to person like you like it but I personally find it sometimes complicated so I listed it in but thanks for the suggestion!!

  • Nick
    NickApr 7, 2021

    Also, u can convert number to string in this way:

    const num = 32
    const str = `${32}`
    
    Enter fullscreen mode Exit fullscreen mode
    • Garvit Motwani
      Garvit MotwaniApr 7, 2021

      That is interesting and thanks for sharing!!

    • Alex Alencar
      Alex AlencarApr 8, 2021

      or

      num + ''

      • Nick
        NickApr 8, 2021

        This method described in the article :/

    • Vladimir C
      Vladimir CMay 28, 2021

      I believe you meant

      const str = `${num}`
      
      Enter fullscreen mode Exit fullscreen mode
  • АнонимApr 7, 2021

    [hidden by post author]

  • Médéric Burlet
    Médéric BurletApr 8, 2021

    for performance you use dates but since you are using console.log you could use console.time()

    console.time("track");
    // do stuff
    console.timeEnd("track")
    
    Enter fullscreen mode Exit fullscreen mode
  • Nikhil Chandra Roy
    Nikhil Chandra RoyApr 8, 2021

    Array.from({length: 10}, (a,b)=> console.log(b)) instant of for loop, Thanks

  • RohitW3code
    RohitW3codeApr 8, 2021

    Very nice , I have a request for you can you publish you articles on our Codeddit Programmer Community it would be a great help to everyone on Codeddit app platform.
    play.google.com/store/apps/details...

  • Giovanni Bezicheri
    Giovanni BezicheriApr 8, 2021

    Thanks for the article! Anyway some of those are just tricks that could sacrifice code readibility :)

  • jpotts7
    jpotts7Apr 8, 2021

    Great tips - thanks for sharing!

  • Bret Williams
    Bret WilliamsApr 8, 2021

    Removing duplicates is a good trick. I'll put that one in my back pocket for later.

  • Les Orchard
    Les OrchardApr 8, 2021

    I'd say that Array.from() isn't the most handy as a substitute for Array.map(). Rather, it's handy for transforming iterables that aren't already arrays.

    Like, to get the names of commenters on this page, try this in the dev tools console:

    Array.from(
      document.querySelectorAll('.js-comment-username'),
      el => el.textContent
    )
    
    Enter fullscreen mode Exit fullscreen mode

    The NodeList returned from document.querySelectorAll isn't an array, but this lets you convert it to an array while performing a transformation at the same time.

  • peerreynders
    peerreyndersApr 8, 2021

    Array.from is notable for its intended use of making Array-like data iterable with array methods, such as strings.

    There's another case where it is extremely handy - creating a fresh array with elements initialized from a function.

    const init = (_value, index) => (index + 1) * 3;
    const length = 4;
    const array = Array.from({ length }, init); // [3, 6, 9, 12]
    for (let i = 0; i < length; i += 1) console.assert(array[i] === (i + 1) * 3);
    
    Enter fullscreen mode Exit fullscreen mode

    The issue with Array.prototype.fill() is that:

    • it requires an existing array (to modify)
    • it only places a single constant value into all the elements it replaces.

    And Array.prototype.map() requires an already initialized array.

    With Array.from() an array can be created and initialized with element content that varies by index in one fell swoop.

    • lkarabeg
      lkarabegApr 9, 2021

      I kind of disagree, finding map much more readable.
      Array.from({length: 4}).map((_value, index) => (index + 1) * 3)

      • peerreynders
        peerreyndersApr 9, 2021

        With

        const array = (new Array(length)).fill().map(init);
        
        Enter fullscreen mode Exit fullscreen mode

        it always ground my gears that to arrive at the desired array another disposable array had to be created and "filled" just to convey that I want length elements. And

        const array = (new Array(length)).fill();
        array.forEach((_v, i, a) => {
          a[i] = (i + 1) * 3;
        });
        
        Enter fullscreen mode Exit fullscreen mode

        was clunky enough to make me want to use a for loop.

        So if I'm are already using Array.from() I might as well use the optional mapFn and thisArg parameters.

        function init(_value, index) {
          return (index + 1) * this.factor;
        }
        
        const config = { length: 4 };
        const two = { factor: 2 };
        const three = { factor: 3 };
        const array2 = Array.from(config, init, two);
        const array3 = Array.from(config, init, three);
        
        const checkArray = (expected, actual) => {
          const actualMatches = (value, index) => value === actual[index];
          console.assert(
            expected.length === actual.length && expected.every(actualMatches),
            'array mismatch - expected: %o actual: %o',
            expected,
            actual
          );
        };
        const TWOS = [2, 4, 6, 8];
        const THREES = [3, 6, 9, 12];
        checkArray(TWOS, array2);
        checkArray(THREES, array3);
        
        Enter fullscreen mode Exit fullscreen mode

        ... but that's just me.

  • Strat Barrett
    Strat BarrettApr 8, 2021

    I'm a big fan of !! which gets the boolean value of (pretty much) anything:

    let truthiness = !!12       //=> true
    let truthiness = !!0        //=> false
    let truthiness = !!'string' //=> true
    let truthiness = !!''       //=> false
    // BUT LOOK OUT FOR OBJECTS... 👀
    let truthiness = !![]       //=> true
    let truthiness = !!{}       //=> true
    
    Enter fullscreen mode Exit fullscreen mode

    ! is the opposite so !! becomes the boolean value !! 😄

    • Garvit Motwani
      Garvit MotwaniApr 8, 2021

      Thanks for sharing! 🙏🙏

    • Chris
      ChrisApr 10, 2021

      The Boolean() constructor is another great way to interpret falsey values.

  • John McCambridge
    John McCambridgeApr 9, 2021

    This is awesome

  • Mohamed Ahmed
    Mohamed AhmedApr 10, 2021

    thanks for this nots

  • Danz
    DanzApr 10, 2021

    Love it thanks great tricks

  • Amir Salehi
    Amir SalehiApr 10, 2021

    Nice 👍

  • АнонимApr 10, 2021

    [hidden by post author]

  • АнонимApr 10, 2021

    [hidden by post author]

  • George Delaportas (ViR4X)
    George Delaportas (ViR4X)Apr 10, 2021

    G R E A T work...

    There are also many other great tricks you can do to optimize code, add quality and also provide C#-like or JAVA-like paradigms to JavaScript.

    Check my web framework and especially the JS extensions for more cool ideas.

    github.com/g0d/micro-MVC
    github.com/g0d/micro-MVC/tree/mast...

  • cubiclesocial
    cubiclesocialApr 11, 2021

    We can also use that to swap values fast

    Swapping variables with an array isn't going to be faster (performance-wise) than just swapping the variables with the traditional method of using a temporary variable.

    stackoverflow.com/questions/162016...

    One of the first comments on using a temporary array is that it is roughly two times slower than a variable swap.

    Javascript processes most accesses by reference. So assigning to a temporary variable doesn't copy anything but a memory address. Creating an array, on the other hand, is almost certainly going to: Hit the memory allocation pool, add two variables to the array, update the length of the array (for no good reason), then immediately extract them back out of the array, and release the array back into the memory pool. Without even having to test that, the former is obviously faster than the latter. Swapping vars happens often in software, and usually in a loop, so writing performant code vs. one-liners is more important here.

  • thangdangblog
    thangdangblogApr 11, 2021

    Thank you for sharing! Your post helps me improve my skills in Javascript!

  • Nick Haralampopoulos
    Nick HaralampopoulosApr 12, 2021

    Nice article Garvit! I usually use the .map() substitute when creating arrays with pre-filled values. One little mistake though. array.length is a property in JavaScript not a method. It is a method in Java, C++ and others but not in JavaScript.
    developer.mozilla.org/en-US/docs/W...
    Thank you again for the nice article.

  • Emmanouil Liakos
    Emmanouil LiakosApr 12, 2021

    Another nice tip is that arrays passed to template literals get coerced to comma-separated strings like this:

    const fruits = ['apples', 'oranges'];
    console.log(${fruits}); // 'apples,oranges'

  • Ece
    EceApr 12, 2021

    Daaamn, this is very useful.

  • Kasia
    KasiaApr 13, 2021

    it`s ok

  • IQ Seviyesi
    IQ SeviyesiApr 13, 2021

    Perfect tricks :)

  • Yuri Filatov
    Yuri FilatovApr 13, 2021

    This is an amazing job!

  • Ben Davies
    Ben DaviesApr 19, 2021

    Hey quick question when changing the length of the array to remove items from the array does this not cause a memory leak because of how arrays are stored, or does the garbage collector understand this change and then clean up the memory as necessary

  • Sinval Felisberto
    Sinval FelisbertoJun 6, 2021

    Thank you Kindly, Garvit!
    Greetings from Brazil!

Add comment