zer0Id0l
zer0Id0l

Reputation: 1444

Javascript String Array-Like-Object behaviour

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?

Upvotes: 0

Views: 59

Answers (3)

obfish
obfish

Reputation: 667

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.

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370699

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';

Upvotes: 3

Adrian Brand
Adrian Brand

Reputation: 21638

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.

Upvotes: 0

Related Questions