When do I initialize variables in JavaScript with null or not at all?

后端 未结 5 1719
攒了一身酷
攒了一身酷 2020-12-23 09:27

I have seen different code examples with variables declared and set to undefined and null. Such as:

var a; // undefined - unintentional value, object of type         


        
5条回答
  •  情歌与酒
    2020-12-23 10:17

    I don't think there's a particular better way of doing things, but I'm inclined to avoid undefined as much as possible. Maybe it's due to a strong OOP background.

    When I try to mimic OOP with Javascript, I would generally declare and initialize explicitly my variables to null (as do OOP languages when you declare an instance variable without explicitly initializing it). If I'm not going to initialize them, why even declare them in the first place? When you debug, if you haven't set a value for a variable you watch, you will see it as undefined whether you declared it or not...

    I prefer keeping undefined for specific behaviours:

    • when you call a method, any argument you don't provide would have an undefined value. Good way of having an optional argument, implementing a specific behaviour if the argument is not defined.
    • lazy init... in my book undefined means "not initialized: go fetch the value", and null means "initialized but the value was null (eg maybe there was a server error?)"
    • arrays: myArray[myKey] === null if there is a null value for this key, undefined if a value has never been set for this key.

    Be careful though, that myVar == null and myVar == undefined return the same value whether myVar is undefined, null or something else. Use === if you want to know if a variable is undefined.

提交回复
热议问题