0

Adding new value to string

When I run above code in Chrome dev console, I do not get any error. But when same code runs via js loaded on a webpage I receive this exception - Cannot create property 'name' on string 'some string'

Can someone please tell me why there is different behaviour in above 2 cases?

3 Answers 3

3

Your webpage must be running that snippet of code in strict mode, in which assigning to properties of a string will throw an error:

'use strict';
const str = 'foo';
str.bar = 'bar';

In sloppy mode, it'll just fail silently:

const str = 'foo';
str.bar = 'bar';

Sign up to request clarification or add additional context in comments.

2 Comments

But if you console.log(str.bar) you get undefined. It is not valid to add a property to a value object.
Indeed, it's not valid, it just won't throw an error in sloppy mode: In sloppy mode, it'll just fail silently
0

Strings are a value objects as in they have a value not a reference to an instance of an object, they cannot have properties set with a["name"] like reference objects can.

a[3] is the 4th character in the string, a[0] being the first.

Comments

0

Let's see this case

const a = "a"
Object.isFrozen(a) // true
const b = new String("b")
Object.isFrozen(b) // false

From this section, we could see that String objects are not necessarily frozen. Only those string literals are frozen (I think it's because they are shared in a pool. If they are not frozen, you can create properties on one place to affect the code elsewhere) However, the explicitly constructed String objects are independent from the pool, thus not frozen.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.