0

I came across some strange (legacy?) JS syntax this morning which boiled down to:
var example = "String".Property = "Value";

Before altering this code, I couldn't find a valid case for this implementation that I am aware of...

var example = "String".Property = "Value";
console.log(example);

"String".Property = "Value";
console.log("String".Property);
console.log(String.Property);

What actually happens to "String".Property in the first part of the above snippet, does it just get discarded immediately after being assigned ?

2
  • "String" is a literal string, and since you don't keep a reference to it it will be garbage collected whether you assign a property to it or not. Commented Sep 19, 2018 at 22:37
  • 4
    I don't know where you found this code, but it's bad. Commented Sep 19, 2018 at 22:39

1 Answer 1

3

String literals are string primitive values. When followed by a dot (.) operator, they are implicitly converted to a String instance.

The statement

var example = "String".Property = "Value";

is equivalent to

var example = "Value";

There is no point to the .Property reference.

Subsequently,

"String".Property = "Value";

has no net effect on the global environment, because the string constant "String" is converted to a String instance and the property is set, but then the object is discarded because it isn't assigned to anything.

Every use of the string constant "String" that results in an implicit object creation will cause a new unique object to be created.

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

3 Comments

Indeed, typeof "foo" !== typeof new String("foo")
Multi-part answers should be closed as "Too Broad" and not answered.
Seeing obscure code like this always makes me question why it was implemented in the first place / what don't I know. Thanks for the clarity.

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.