[ Web Proxy ]
URL:
Viewing: https://javascript.info/task/string-new-property [Back]  [Original]

Can I add a string property?
EN

We want to make this open-source project available for people all around the world.

Help to translate the content of this tutorial to your language!

    Search on Javascript.info:
    Search in the tutorial:
    Light themeDark theme
    DanskEnglishEspaolFranaisIndonesiaItalianoTrkeOzbek
    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?

    solution

    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? Lets replay whats 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 cant store additional data.


    Web Proxy Viewer  |  New URL  |  Original Page