Declaring vs Initializing a variable?

前端 未结 7 1126
暖寄归人
暖寄归人 2020-12-06 05:48

I\'m curious to know the difference between declaring a variable, and initializing a variable. e.g.

var example; // this is declaring

var example = \"hi\" /         


        
相关标签:
7条回答
  • 2020-12-06 06:47

    Taken straight from the MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined :

    The global undefined property represents the primitive value undefined. It is one of JavaScript's primitive types.

    Simply declaring a variable in Javascript, such as var example initializes it to the primitive value of undefined. That means the following two expressions are equivalent:

    //equivalent expressions
    var ex1;
    var ex2 = undefined;
    
    //true!
    alert(ex2 === ex1);

    What I don't know and can't test at this time is how far back in web browser history the alert will display true. For example, does this alert work in IE6 or some obscure Blackberry phone? I can't say for certain this is universal but it at least works in the latest versions of Firefox, Chrome, and Safari at the time of writing.

    0 讨论(0)
提交回复
热议问题