0

When predefining class properties in a constructor is it more appropriate to initialize the property with null or undefined?

class PostViewer {
    constructor() {
        this.frontend = true
        this.editor = undefined // or should use `null`?
        this.key = undefined // or should use `null`?
        this.container = undefined // or should use `null`?
    }
}
Phil M
  • 432
  • 7
  • 16
  • This seems entirely arbitrary, so I don't see any way for someone to offer a factual answer that isn't just their opinion. – loganfsmyth Feb 06 '18 at 00:29
  • If you set it as undefined you're redundant, better let it without assignation. – Ele Feb 06 '18 at 01:10
  • I have been declaring them because the classes are being used within a Vue project... and by declaring the property in the constructor I don't have to add and declare the property as a watched one with vue [ex: `window.vueeventbus.$set(obj, 'key', key)`] – Phil M Feb 06 '18 at 01:20

2 Answers2

2

I would recommend not setting them at all, or if you must, use null.

The reason:

Setting them to undefined is (almost) indistinguishable from not setting them at all. The only difference being that using the in operator (and related functions, such as hasOwnProperty) would return true if those fields are explicitly set to undefined.

So it would be better to use null so that both types of common existence checks: "foo" in bar and bar.foo !== undefined both return the same value (either they're both true, or both false).

CRice
  • 29,968
  • 4
  • 57
  • 70
  • 3
    If performance is a concern, not setting them at all is a big performance hit because it means engines can't optimize instances for the correct hidden class up front. – loganfsmyth Feb 06 '18 at 00:27
0

By default the javascript assigns undefined to its variables. But null is a type in java on the other hand undefined is premitive value. So that depends on the use, what it should be. But if you compare them

undefined == null

it will return true. But

var somevar;

and

var somevar=undefined;

are also same in most cases.

Sharjeel Ahmed
  • 439
  • 1
  • 3
  • 11