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 executed for the following arrow function context: let message = { hello: 'Hello', names: ['Sue', 'Joe'], showMessage: function() { this.names.forEach(name => { console.log(this.hello + ' ' + name); }); } }?

  1. Hello Sue

  2. undefined Sue

  3. Hello Sue and Hello Joe

  4. Hello Joe

The correct answer is: Hello Sue and Hello Joe

When the method `showMessage` is executed on the `message` object, the arrow function inside the `forEach` method captures the context of `this` from the enclosing scope, which is the `showMessage` method itself. This means that within the arrow function, `this` refers to the `message` object, not the global object or any other context. The `showMessage` method iterates through each name in the `names` array using `forEach`. For each name, it constructs a string that combines the `hello` property of the `message` object with the current name being processed. Therefore, when iterating over the `names` array, the console will log: 1. For the first iteration with `name` equal to 'Sue': it constructs and logs "Hello Sue". 2. For the second iteration with `name` equal to 'Joe': it constructs and logs "Hello Joe". As a result, the output generated by executing `message.showMessage()` will be two separate lines in the console: "Hello Sue" and "Hello Joe". Since the choice provided indicates the inclusion of both greetings, it correctly identifies the output as "Hello Sue and Hello Joe".