Javascript tips

Remove duplicates from an array

It’s a very popular interview question about Javascript arrays, how to extract the unique values from Javascript array. Here is a quick and easy solution for this problem, you can use a new Set() for this purpose. And I would like to show you two possible ways to do it, one with .from() method and second with spread operator (…). var fruits = [“banana”, “apple”, “orange”, “watermelon”, “apple”, “orange”, “grape”, “apple”]; // First method var uniqueFruits = Array.from(new Set(fruits)); console.log(uniqueFruits); // returns [“banana”, “apple”, “orange”, “watermelon”, “grape”] // Second method var uniqueFruits2 = […new Set(fruits)]; console.log(uniqueFruits2); // returns [“banana”, “apple”, “orange”, “watermelon”, “grape”]

Check the code performance with    performance.now()

If you have a portion of code that needs to run really fast, it can be    inspected with performance.now() function. Unlike regular timestamps created with Date.now() the method performance.now() generates high resolution timestamp. /**  * Check the performance with * performance.now()  * */  var startedAt = performance.now(); // Execute the code  for (let i = 0; i < 10 ” 4; i..){   // do nothing  }  // Get the final timestamp.  var endedAt = performance.now();  // Calculate the time taken  console.log( “Your code took ” + (endedAt – startedAt) + ” milliseconds to execute.”);

Multiple conditions in an if statement

If you have to deal with checking a large number of conditions, you can use includes.if([“invoice”, “payment”, “pending”].includes(status)) { }

Merge Objects

The need to merge multiple objects in JavaScript has been around forever,  especially as we started creating classes and widgets with options: const person = { name: ‘David Walsh’, gender: ‘Male’ }; const tools = { computer: ‘Mac’, editor: ‘Atom’ };const attributes = { handsomeness: ‘Extreme’, hair: ‘Brown’, eyes: ‘Blue’ };const summary = {…person, …tools, …attributes}; /* Object { “computer”: “Mac”, “editor”: “Atom”,  “eyes”: “Blue”, “gender”: “Male”, “hair”: “Brown”, “handsomeness”: “Extreme”, “name”: “David Walsh”, } */

Difference b/w === and

The == (or !=) operator performs           an automatic type conversion if needed. The === (or !==) operator will not perform any conversion. It compares the value and the type, which could be considered faster than ==. [10] === 10      // is false [10]  == 10       // is true ’10’ == 10        // is true ’10’ === 10      // is false []   == 0         // is true  ” == false      // is true   but true == “a” // is false  ” ===   false // is false

Throttle and debounce

Setting limits on how much JavaScript gets executed at once can help fine tune your application's performance. Throttling sets the maximum number of times that a function may be called over time, while debouncing ensures that a function isn't called again until a designated amount of time passes. Medium has a good tutorial for throttling and debouncing JavaScript code. If you need a little extra support, there are several code compression tools designed to help developers optimize their applications' JavaScript performance. Code compression, or code minification, removes unnecessary characters from source code, which results in smaller file sizes and faster load times. Here is a sampling of the the top tools for tuning JavaScript code:

Animate with requestAnimationFrame

Animations should ideally render at 60 FPS. JavaScript libraries like Anime.js and Gsap are helpful for creating quick animations, but if your JavaScript animations are still running slow, try using the requestAnimationFrame() method to get them up to speed.

Prefer async and defer

If you want script tags to load asynchronously, or to defer until the rest of the page has finished loading, you can add the async or defer attributes:

// load example.js without interrupting your webpage's rendering
<script src="example.js" async></script>

// load example.js after the page has finished loading
<script src="example.js" defer></script>

The graph below shows the difference between synchronous and asynchronous loading. As we can see, synchronous assets need to wait for the previous asset to finish loading before a new one can start; whereas asynchronously loaded assets can load at the same time.

Favor native functions and constructs

Rather than writing your own algorithms or relying too much on host objects, take advantage of native functions and constructs as much as you can. ECMAScript lists hundreds of native constructs for you to choose from.

Use the local scope (this)

Speaking of which, this allows you not only to write asynchronous code with callbacks, but it also helps boost performance by reducing dependency on global variables or closures residing higher in the scope chain. Conversely, you should avoid the with keyword because it modifies the scope chain, which drags down performance. You can rewire the scope variable using the call() and apply() methods as follows:

var Person = Object.create({
    init: function(name) {
        this.name = name;
    },
    do: function(callback) {
        callback.apply(this);
    }
});

var bob = new Person('bob');

bob.do(function() {
    alert(this.name); // 'bob' is alerted because 'this' was rewired
});