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 the output be when message.showMessage() is called in the context of: let message = { hello: 'Hello', names: ['Sue', 'Joe'], showMessage: function() { this.names.forEach(function(name) { console.log(this.hello + ' ' + name); }); } }?

  1. Hello Sue

  2. undefined Sue

  3. undefined Joe

  4. undefined Sue and undefined Joe

The correct answer is: undefined Sue and undefined Joe

In the given code snippet, the `showMessage` method calls `this.names.forEach`, which executes a callback function for each element in the `names` array. However, it's important to note how `this` behaves within that callback function. In JavaScript, the value of `this` inside a regular function (as opposed to an arrow function) does not refer to the object that invokes the method (`message` in this case). Instead, it refers to the global object or `undefined` in strict mode when the function is called in a different context, like the way it is within the `forEach` method. As a result, inside the callback of `forEach`, `this.hello` will not refer to `message.hello`. Instead, it will evaluate to `undefined`, leading to the output being `undefined` concatenated with each name. So, when "Sue" and "Joe" are iterated over, the output becomes: - For "Sue": `undefined Sue` - For "Joe": `undefined Joe` This leads to the conclusion that when `message.showMessage()` is invoked, the final output will be `undefined Sue` and `undefined Joe`, reflected accurately in the option indicating both outputs