Prepare for the Salesforce JavaScript Developer Exam. Utilize comprehensive quizzes, flashcards, and multiple choice questions with hints and explanations. Boost your exam readiness!

Practice this question and more.


What will be the output of the following code: const person = { name: 'Lydia' }; function sayHi(age) { return `${this.name} is ${age}`; } console.log(sayHi.call(person, 21)); console.log(sayHi.bind(person, 21));?

  1. undefined is 21 Lydia is 21

  2. function function

  3. Lydia is 21 Lydia is 21

  4. Lydia is 21 function

The correct answer is: Lydia is 21 function

The output of the provided code involves understanding how the call and bind methods work in JavaScript. When invoking `sayHi.call(person, 21)`, the call method is executed with `person` as the context (value of `this`). Therefore, `this.name` refers to `person.name`, which is 'Lydia'. The function returns the string `'Lydia is 21'`, which gets printed to the console. In the second console log, `sayHi.bind(person, 21)` is called. The bind method does not execute the function immediately; rather, it creates and returns a new function. This new function, when called, will have `this` set to `person` and the first argument set to `21`. Since the current log statement is just referencing the function returned by bind, it outputs the text "function" instead of executing it. Thus, combining both outputs, the final output is `Lydia is 21` followed by `function`, which is why that particular choice reflects the behavior of the code accurately.