Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a.style.display: Value assigned to primitive will be lost

Consider this JavaScript snippet:

var a = document.createElement("a");
a.style.display = "none";

IntelliJ IDEA 2016.2 highlights a.style.display and gives this hint:

Value assigned to primitive will be lost

Checks for improper usage of wrappers for JavaScript primitive types. Also, warning will be produced when property of primitive type is modified, as assigned value will be lost

IntelliJ IDEA hint

CSSStyleDeclaration is not a primitive type, thus the assignment to display won't be lost.

String is a wrapper type. How am I using it (improperly)?

The code seems to work fine in Chrome and Edge. What's the deal?

like image 606
xehpuk Avatar asked Jul 19 '16 16:07

xehpuk


People also ask

What are default values assigned to primitive data types in Java?

Default Values Assigned to Primitive Data Types in Java Data Type Size Byte 1 byte Short 2 bytes Int 4 bytes Long 8 bytes 4 more rows ...

Where does the default display value come from in HTML?

In HTML, the default display property value is taken from the HTML specifications or from the browser/user default style sheet. The default value in XML is inline, including SVG elements. ? The numbers in the table specify the first browser version that fully supports the property.

What is display property in HTML?

More "Try it Yourself" examples below. The display property specifies the display behavior (the type of rendering box) of an element. In HTML, the default display property value is taken from the HTML specifications or from the browser/user default style sheet.

Is it a good programming style to rely on default values?

However, relying on such default values is not considered a good programming style. Now as we know Initializing a variable means to give an initial value to a variable before using it.


1 Answers

There's nothing improper in your code, IntelliJ's type inference is getting a bit confused (this aspect of JavaScript is particularly confusing).

Its linter sees a string and assumes you will try something like this:

var primitive = "september";
primitive.vowels = 3;

primitive.vowels;
// => undefined

Which would lead to a 'lost' value.

To further understand this weird part of JavaScript, I recommend Angus Croll's excellent in-depth article here.

like image 133
ryanpcmcquen Avatar answered Sep 26 '22 09:09

ryanpcmcquen