GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

No menu could be recovered. Follow the blue links in the page.

This view

  • Original page
  • New address

GeezerVison is showing javascript.info — Can I add a string property?

  • Tutorial
  • The JavaScript language
  • Data types
  • Methods of primitives
back to the lesson

Can I add a string property?

importance: 5

Consider the following code:

let str = "Hello";

str.test = 5;

alert(str.test);

What do you think, will it work? What will be shown?

Try running it:

let str = "Hello";

str.test = 5; // (*)

alert(str.test);

Depending on whether you have use strict or not, the result may be:

  1. undefined (no strict mode)
  2. An error (strict mode).

Why? Let’s replay what’s happening at line (*):

  1. When a property of str is accessed, a “wrapper object” is created.
  2. In strict mode, writing into it is an error.
  3. Otherwise, the operation with the property is carried on, the object gets the test property, but after that the “wrapper object” disappears, so in the last line str has no trace of the property.

This example clearly shows that primitives are not objects.

They can’t store additional data.

You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.