Saturday, April 11, 2020

Getter and Setter in JS

Let us suppose we have an object called User like this:
1
2
3
4
const user = {
    firstName: 'A',
    lastName: 'B',
}

Now suppose we want to return the full name of the function it will something be like this:

1
console.log(`${user.firstName} ${user.lastName}`)

But this is a naive approach and in case if we have to add something extra in the statement, we have to change every where, instead the better way is to give a function that will return this expression/value like:

1
2
3
4
5
6
7
8
9
const user = {
    firstName: 'A',
    lastName: 'B', 
    fullName () { // previous version was like fullName: function () {...} but changed in ES6
        return `${this.firstName} ${this.lastName}`
    }
}

console.log(${user.fullName())

Now this is good but:
  1. what if you want to use it as a field and not as a function, I mean, I want to use it something like: console.log(${user.fullName).
  2. And we want to set the value of firstName and lastName on the basis of value we are going to pass to fullName like user.fullName = 'Javascript rocks' 
For that we have 2 keywords called get and set and the use is like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
const user = {
    firstName: 'A',
    lastName: 'B', 
    get fullName () {
        return `${this.firstName} ${this.lastName}`
    }

    set fullName (value) {
        const tokens = value.split(' ');
        this.firstName = tokens[0];
        this.lastName = tokens[1];
    }
}

console.log('Before set', ${user.fullName})

user.fullName = 'Javascript Rocks'.

console.log('After set', ${user.fullName})

Here in this code there are 2 keywords we have seen,

  • get = for accessing the property (at line 4)
  • set = for setting the property (at line 8)
These 2 keywords make the function as a property and that is the reason at line 15 and line 19 we have accessed the fullName without the parenthesis.

That's it, its awesome right :)

Happy Coding :)

For reference, please check out this: https://www.youtube.com/watch?v=bl98dm7vJt0

Thursday, April 9, 2020

debouncing in javascript

So, we have seen the requirements where in which we are required to send the data to the server on an event that might be a click, hover, mouseEnter or anything.

So let us consider we are writing a click event for a button. So the basic code for the same would look something like this:

1
2
3
4
5
$(document).ready(() => {
    $("#btn").on('click', async (event) => {
        // do some api calls or anything
    })
})

Now suppose you are saving/posting the data to the server on every click, in that case if suppose, user clicked the button 2 3 times, it will save the same data 3 times with different ids.

In order to handle this we have 2 options:
  1. either disables the button once you click and enables it once the callback returns
  2. Write a debounce function to handle accidental clicks
Lets see first how debounce function is written.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
const debounce = (fn, delay) => {
    let timeoutId;
    return (...args) => {
        if(timeoutId) clearTimeout(timeoutId);
        timeoutId = setTimeout(() => fn(...args),delay)
    }
}

$(document).on('ready', async() => {
    $('#btn').on('click', debounce(e=> {
        console.log('bye bye')
    }, 2000))
})

Explanation:
  1. In this code, we have first created a higher order function named debounce that is taking 2 params, the callback function and a delay to reset the functionality if, someone triggered the event twice.
  2. The debounce function is returning a function that is calling our callback passed at line 5.
  3. Now, instead of giving the callback directly to the event, we are calling debounce and passing our callback function implementation as well as the delay that is going to wait for certain time, before resetting the timeout.
That's it, this debounce function is a nice way of making sure that the accidental triggering of the events can be stopped and only the last event will be considered. This makes sure that all the events that are triggered before the timeout mentioned are going to keep on cancelling unless user stops the event creation and only the last triggered event is accepted and fires the actual callback.

Happy Coding :)