Predict the output of the following javascript code

const greet = function() {
    console.log(this.message);
};
const obj = {
    message: 'Hello, world!',
};
const boundGreet = greet.bind(obj);
boundGreet();

 

 

 

 

This JavaScript code defines a function greet and an object obj, then creates a bound function boundGreet using the bind() method. Let's break it down:

const greet = function() {
    console.log(this.message);
};
  • Defines a function named greet which logs the message property of the object that this refers to.
const obj = {
    message: 'Hello, world!',
};
  • Creates an object named obj with a property message set to 'Hello, world!'.
const boundGreet = greet.bind(obj);
  • Binds the greet function to the obj object using the bind() method. This means that whenever boundGreet is called, this inside greet will refer to obj.
boundGreet();
  • Calls the boundGreet function. Since boundGreet is bound to the obj object, this.message inside greet will refer to the message property of obj.
  • Therefore, it will log 'Hello, world!' to the console.

So, the output of this code will be:

Hello, world!