WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

JavaScript Β· Intermediate Β· question 27 of 100

What is the "this" keyword in JavaScript, and how does it behave in different contexts?

πŸ“• Buy this interview preparation book: 100 JavaScript questions & answers β€” PDF + EPUB for $5

In JavaScript, the this keyword refers to the current context or scope in which it is used. The behavior of this can vary depending on how it is used and the context in which it is called.

Here are some common examples of how this behaves in different contexts:

Global context - When used in the global context (outside of any function), this refers to the global object (e.g. window in a browser or global in Node.js).

    console.log(this); // Outputs the global object (e.g. window or global)

Function context - When used in a function, the value of this depends on how the function is called. If the function is called as a method of an object, this refers to the object. If the function is called without any context, this refers to the global object.

    var obj = {
        name: "John",
        sayHello: function() {
            console.log("Hello, my name is " + this.name);
        }
    };
    
    obj.sayHello(); // Outputs "Hello, my name is John"
    
    var sayHello = obj.sayHello;
    sayHello(); // Outputs "Hello, my name is undefined" (because there is no context for `this`)

Event context - When used in the context of an event listener, this refers to the element that triggered the event.

    document.querySelector("button").addEventListener("click", function() {
        console.log(this); // Outputs the button element that was clicked
    });

Constructor context - When used in the context of a constructor function, this refers to the newly created object that is being constructed.

    function Person(name, age) {
        this.name = name;
        this.age = age;
    }
    
    var john = new Person("John", 30);
    
    console.log(john.name); // Outputs "John"

In summary, the this keyword in JavaScript refers to the current context or scope in which it is used. Its behavior can vary depending on how it is used and the context in which it is called. Understanding the behavior of this is important for writing effective and maintainable JavaScript code.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic JavaScript interview β€” then scores it.
πŸ“ž Practice JavaScript β€” free 15 min
πŸ“• Buy this interview preparation book: 100 JavaScript questions & answers β€” PDF + EPUB for $5

All 100 JavaScript questions Β· All topics