Is there a difference between getPropertyValue() and the bracket notation [] for CSSStyleDeclaration?

Viewed 5733

For example, we need to access body's padding-right

let el = document.querySelector('body');
let style = window.getComputedStyle(el);

Thanks to this explanations, it's clear that it could be safely done by:

style.paddingRight

or

style.getPropertyValue('padding-right')

But, it seems that this also works fine:

style['padding-right']

Is there are any differences? Thx

3 Answers

One difference is that getPropertyValue is guaranteed to return a string, while with the direct property access (JavaScript's bracket or dot notation) you could get undefined. getPropertyValue will return the empty string in that case.

let el = document.querySelector('body');
let style = window.getComputedStyle(el);

console.log(style.something === style.getPropertyValue('something')); // false

Is there a difference:

1) Yes

[] - Accessing properties using bracket notation like this: style['padding-right'] is defined in the runtime specification of JavaScript (ECMAScript). It is a well known mechanism for accessing properties on objects: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

getPropertyValue() - is specified in the CSSOM specification as a method for accessing CSS properties from a CSS style object.

2) No - not at all for practical purposes

3) Yes and No - opinions will flare about best practices etc. It is entirely possible (although not probable) the CSSOM specification may change and store that property in some other location on the object. That would render the brackets useless in your code and break.

Reason why style['padding-right'] also works.

>function A() { this.a = 5;}
//undefined
>a = new A()
//A {a: 5}
>a['a']
//5

Difference already mentioned by @trincot.

Related