js-test-24

Can you add a custom field to a regular JS string?

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

The answer to this problem will depend on whether you’ve added the ’use strict’ flag at the beginning of your script.

The result will be:

So what’s the deal?

In the second line, when you try to access s.user, JS creates the wrapper object under the hood.

If you’re using the strict mode, any modification attempt will throw an error.

If you’re not using the strict mode, then the execution will continue and the new property user will be added to the wrapper object.

However, once we’re done with the second line of code, the wrapper object is disposed and the user property is gone, so undefined is logged to the console.


ANSWER: You can’t add properties to primitive values in JS. The result will depend on the presence of the 'use strict' flag.