JS Handbook

Subscribe to my newsletter and never miss my upcoming articles

Q. When should you use Arrow functions in JavaScript? What is the `this ?

Apart from being cleaner to read, arrow functions help in avoiding bugs related to the 'this' within callbacks, it because easier for a programmer to predict the value of this.

In simpler terms, when you use a formal function, this points to the context where the function is called. In case of an arrow function, this points to the context where the function was declared.

In JavaScript, the value of this depends upon the context where the function was actually called and not where it is defined. You can force a specific value for this using call, apply or bind. Once you’ve passed a method as a callback, you have no idea how it will be called, and thus no idea what this will be.

Here are some rules:

  • If the new keyword is used when calling the function, this inside the function is a brand new object.
  • If apply, call, or bind are used to call/create a function, this inside the function is the object that is passed in as the argument.
  • If a function is called as a method, such as obj.method() — this is the object that the function is a property of.
  • If a function is invoked as a free function invocation, meaning it was invoked without any of the conditions present above, this is the global object. In a browser, it is the window object. If in strict mode ('use strict'), this will be undefined instead of the global object.
  • If multiple of the above rules apply, the rule that is higher wins and will set the this value.
  • If the function is an ES2015 arrow function, it ignores all the rules above and receives the this value of its surrounding scope at the time it is created.

Q. Write a debounce function?

const debounce = (func, wait) => {
  // TODO: Your code here
  let timeoutId;
  return (...args) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
      func(...args);
    }, wait);
  }
}

const greet = (country) => {
  console.log(`Welcome to ${country}!`);
}

const debouncedGreet = debounce(greet, 2000);
debouncedGreet("Taiwan (1)");
debouncedGreet("Vietnam (2)");
debouncedGreet("India (3)");
debouncedGreet("Singapore (4)");

Search bar de-bounce example

No Comments Yet