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

  1. undefined Sue

  2. Hello Sue

  3. Hello Joe

  4. Hello Sue and Hello Joe

The correct answer is: Hello Sue and Hello Joe

The output of the `message.showMessage()` function is indeed "Hello Sue and Hello Joe." This is a result of the way the `forEach` method iterates over the `names` array and how the `self` variable, which references the current context of `this`, is utilized within the inner function. When `showMessage` is invoked, it first sets the `self` variable to the value of `this`, which points to the `message` object. The `forEach` method then takes each element from the `names` array and provides it to the inner function as `name`. Inside this inner function, `console.log(self.hello + ' ' + name);` constructs a string that concatenates `self.hello` (which is "Hello") with the current `name` from the iteration. Thus, during the first iteration, `name` is "Sue," leading to the output "Hello Sue." In the second iteration, `name` becomes "Joe," resulting in the output "Hello Joe." These two messages are printed sequentially, producing the complete output of "Hello Sue" followed by "Hello Joe." Therefore, when combined, the correct interpretation of the output as a single statement