What will be the outcome of the following: let message = { hello: 'Hello', names: ['Sue', 'Joe'], showMessage: function() { this.names.forEach(function(name) { console.log(this.hello + ' ' + name); }); } }; message.showMessage();?

Prepare for the Salesforce JavaScript Developer I Certification Exam with quizzes, flashcards, and detailed explanations. Enhance your understanding and boost your confidence to ace your certification!

Multiple Choice

What will be the outcome of the following: let message = { hello: 'Hello', names: ['Sue', 'Joe'], showMessage: function() { this.names.forEach(function(name) { console.log(this.hello + ' ' + name); }); } }; message.showMessage();?

Explanation:
In the provided code snippet, you have an object named `message` that contains a property `hello`, an array `names`, and a method `showMessage`. The `showMessage` method uses `forEach` to iterate over the `names` array and log a message combining the `hello` property with each name in the array. The key aspect to understand here is how the `this` keyword works in JavaScript, particularly in the context of how it's resolved within function scopes. In the `showMessage` method, `this.names.forEach(...)`, the scope of `this` does not refer to the `message` object within the inner function created by `forEach`. Instead, it refers to the global context (or `undefined` in strict mode) because the inner function does not have its own `this` context and is not bound to the `message` object. As a result, when you try to access `this.hello` inside the inner function, it evaluates to `undefined` since `this` does not point to the `message` object anymore. Consequently, the output of the `console.log` statement will result in `undefined` for the `hello` property, followed by each name in the

In the provided code snippet, you have an object named message that contains a property hello, an array names, and a method showMessage. The showMessage method uses forEach to iterate over the names array and log a message combining the hello property with each name in the array.

The key aspect to understand here is how the this keyword works in JavaScript, particularly in the context of how it's resolved within function scopes. In the showMessage method, this.names.forEach(...), the scope of this does not refer to the message object within the inner function created by forEach. Instead, it refers to the global context (or undefined in strict mode) because the inner function does not have its own this context and is not bound to the message object.

As a result, when you try to access this.hello inside the inner function, it evaluates to undefined since this does not point to the message object anymore. Consequently, the output of the console.log statement will result in undefined for the hello property, followed by each name in the

Subscribe

Get the latest from Examzify

You can unsubscribe at any time. Read our privacy policy