What's the difference between variable definition and declaration in JavaScript?

后端 未结 8 1351
情话喂你
情话喂你 2020-12-03 03:54

Is this a variable definition or declaration? And why?

var x;

..and is the memory reserved for x after this st

相关标签:
8条回答
  • 2020-12-03 04:27

    Declaring a variable is like telling the (javascript) compiler that this token x is something I want to use later. It does point to a location in memory, but it does not yet contain a value. ie. it is undefined

    var x;
    

    defining it means to give it a value which you can either do it like:

    x = 10; // defining a variable that was declared previously
    

    or like this:

    var y = 20; // declaring and defining a variable altogether.
    

    http://msdn.microsoft.com/en-us/library/67defydd(v=vs.94).aspx http://www.w3schools.com/js/js_variables.asp

    0 讨论(0)
  • 2020-12-03 04:31

    var x is a declaration because you are not defining what value it holds but you are declaring its existence and the need for memory allocation.

    var x = 1 is both declaration and definition but are separated with x being declared in the beginning while its definition comes at the line specified (variable assignments happen inline).

    I see that you already understand the concept of hoisting but for those that don't, Javascript takes every variable and function declaration and brings it to the top (of its corresponding scope) then trickles down assigning them in order.

    You seem to know most of this already though. Here's a great resource if you want some advanced, in-depth exploration. Yet I have a feeling you've been there before.

    Javascript Garden

    PS - your analogy between C variable dec/def and JS was spot on. What you read on Wikipedia was correct.

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