What is call, apply & bind in JavaScript?

By Prajwal Haniya

Tech-letter #2 | December 17,2022

  1. What is trie data structure in JavaScript?

    Trie is one of the important data structures to handle strings. It is also called a prefix tree. A trie consists of an empty root node and is always a set of linked nodes. The size of the trie depends on the number of alphabets.

    • Each node can point to null or other children nodes.

    Before implementing the Trie you need to understand how ‘this’ works in JavaScript.

    Will be explaining the trie data structure in a detailed manner in the upcoming techletters. While studying this, I found that there needs a more understanding of some other concepts, so will be explaining this later.

  2. How does ‘this’ work in JavaScript?

    For a beginner, this is one of the most confusing topics in JS. But, hold on, you can understand this with a bit amount of experience in coding. But, here I will try to explain it in a very simple manner as possible.

    The keyword this is really important in order to write advanced JavaScript code. Basically, the this keyword allows you to

    • Identify the objects within the current execution context.
    • In a function, this is referred to a global object. Whereas this is undefined inside a function when used in strict mode.
    • this may be different each time a function is called.
    • The bind() method has the ability to set the value of a function’s this.

    A deeper understanding of this can be found on mdn docs

  3. What is an Execution Context?

    A parser understands the code line by line. It understands the syntax & what the code is expected to do. The JavaScript engine receives the JavaScript source code & compiles it to the binary instructions also called machine code that a machine can understand.

    Whenever the browser encounters the JavaScript code, it sends it to the JavaScript engine to execute. And then the JavaScript engine creates an environment that is an execution context for the execution of that particular code.

    A complete understanding of how the JS code is executed can be found in this wonderful article.

  4. What is call(), apply(), & bind() ?

    As the JavaScripts engine executes the code, the functions & variable names get added to the Environment Record. This process of adding is called binding. Each Execution Context contains the environment record.

    Let us understand biding with an example:

    const obj = {
        name: 'Praj',
        address: 'Bengaluru',
        message: function () {
            console.log(`${this.name} is in ${this.address}`);
        },
    };
    

    In the above example, the this is bound to the obj. Even if the object is passed dynamically, this will refer to that particular object that you have sent.

    When you pass the object dynamically, then it is nothing but a process of explicit binding.

    call()

    Let us find out how call works with an example

    let message = function () {
        console.log(`${this.name} is in ${this.address}`);
    };
    
    const obj = {
        name: 'Praj',
        address: 'Bengaluru',
    };
    
    message.call(obj);
    

    Here, the obj is passed as a parameter to the call method for the message function. The message function takes the obj as the context. If multiple objects with the same properties are passed then the context of the first object is considered.

    apply()

    The apply method is similar to the call method, but it allows the array to be passed as a parameter, whereas the call won’t.

    let message = function (language1, language2) {
        console.log(
            `${this.name} is in ${this.address}. And knows to code in ${language1}, & ${language2}`
        );
    };
    
    const obj = {
        name: 'Praj',
        address: 'Bengaluru',
    };
    
    const codingLanguages = ['JavaScript', 'Python'];
    
    message.apply(obj, codingLanguages);
    

    Did you notice how beautiful it was. If yes! give it a try yourself in coding this.

    bind()

    The bind method is similar to call, but it allows you to assign it to a variable name and then later invoke it as a function. Let me demonstrate with an example

    let message = function (language1, language2) {
        console.log(
            `${this.name} is in ${this.address}. And knows to code in ${language1}, & ${language2}`
        );
    };
    
    const obj = {
        name: 'Praj',
        address: 'Bengaluru',
    };
    
    const codingLanguages = ['JavaScript', 'Python'];
    
    const newFunction = message.bind(
        obj,
        codingLanguages[0],
        codingLanguages[1]
    );
    newFunction();
    

    The bind method basically returns a function that can be invoked later.