Brett Brett - 1 year ago 219
Javascript Question

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
will be lost?

Answer Source

PHPStorm warns you about creating objects of String. Each of new instance will not contain locale variable as it's not declared in String.prototype. The code below should explain it.

var index = 1;
function test(value) {
	document.body.innerHTML += index++ + " " + value;
  document.body.innerHTML += "</br>";

test(String.locale); // 1 - check if locale exists

String.locale = "locale";
test(String.locale); // 2 - should return "locale"

String.prototype.locale = "other locale";
test(String.locale); // 3 - should strill return "locale"
test(String.prototype.locale); // 4 - should return "other locale"

test("".locale); // 5 - "other locale"
test(String("").locale); // 6 - "other locale"
test((new String("")).locale);  // 7 - "other locale"

String.locale = "locale";
test((new String("")).locale); // 8 - still "other locale", "locale" variable is not used when creating objects from "String" thus it's lost in all instances of this constructor


It seems PHPStorm warns about those primitives only:

  • Number
  • String
  • Boolean
  • null (not Null, null)

It's IDE specific behavior. It doesn't notify about custom objects.

EDIT After some research I understood I was wrong. It seems my answer wasn't related to the PHPStorm warning.

When you create a primitive variable and set it's property like so: primitive.locale = "en-GB" and try to access it by primitive.locale it will be undefined. That's what the warning is trying to tell you.

What I said about primitives still stand, PHPStorm notifies you only about Number, String, Boolean and null.

Check code below:

var someBoolean = true;
someBoolean.locale = "en-GB";
document.body.innerHTML += someBoolean.locale;

document.body.innerHTML += "</br>";

var someString = "test";
someString.locale = "en-GB"
document.body.innerHTML += someString.locale;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download