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

后端 未结 5 1716
攒了一身酷
攒了一身酷 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条回答
  •  萌比男神i
    2020-12-23 10:17

    null is an object.. When something is undefined it is nothing.. it is not an object, neither a string, because it hasn't been defined yet.. obviously.. then it is simply a property with no function..

    example:

    You declare a variable with var but never set it.

    var foo; 
    alert(foo); //undefined.
    

    You attempt to access a property on an object you've never set.

    var foo = {};
    alert(foo.bar); //undefined
    

    You attempt to access an argument that was never provided.

    function myFunction (foo) {
      alert(foo); //undefined.
    }
    

提交回复
热议问题