DEV Community

Cover image for JavaScript Interview Question #24: Adding new properties to JS strings
Coderslang: Become a Software Engineer
Coderslang: Become a Software Engineer

Posted on • Originally published at learn.coderslang.com on

JavaScript Interview Question #24: Adding new properties to JS strings

js-test-24

Can you add a custom field to a regular JS string? What’s the output?

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

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:

  • undefined if 'use strict' wasn’t specified
  • an error will be thrown if you’re using the strict mode

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.

Learn Full Stack JavaScript

Top comments (2)

Collapse
 
seriouslee13 profile image
SeriousLee13

Damnit, here I am in the dev console trying to mess around with String.proto for like 15 minutes before reading the answer only to find out it can't be done.

Collapse
 
imprimph profile image
Jaswanth

Dude, I am following your articles for a week or so, they are just awesome. Thanks for putting in some great effort and making me learn new tips and tricks in JavaScript.