Search code examples
javascriptphpstorm

Value assigned to primitive will be lost in PhpStorm when setting value of String.locale


I'm using the internationalization library l10n.js and it appears you cannot pass a value to the library to tell it what language you want to run translations on as it attempts to get the value from the clients browser; so I have been told if you actually want to set the locale you would need to do something like:

String.locale = 'en-GB';

In my case I am doing:

String.locale = $('html').attr('lang');

...right at the top of the file.

This works, however in PhpStorm I get the warning that:

Value assigned to this primitive will be lost

I checked this question out and understand why they got the warning, but am unsure in my instance - is it basically just telling me that the current value of String.locale will be lost?


Solution

  • It looks like a false alarm of the PhpStorm type inference system.

    The String is not a primitive in JavaScript language. It is safe to assign a value to the property of the String here because of the String function is an object.

    I suppose that the key idea of the Value assigned to this primitive will be lost could be described with the code:

    > var primitive = "somestring";
    > primitive.someprop = 3;
    3
    > primitive.someprop; 
    undefined
    

    In JavaScript there are 5 primitive types: undefined, null, boolean, string and number. Primitives are not objects and they have no properties. If JavaScript detects an attempt to assign a property to a primitive it will indeed coerce the primitive to an object. But this new object has no references and will immediately become fodder for garbage collection. Therefore a value assigned to primitive will be lost. link