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

后端 未结 8 1408
情话喂你
情话喂你 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:20

    You declare JavaScript variables with the var keyword: var carname;

    After the declaration, the variable is empty (it has no value).

    To assign a value to the variable, use the equal sign var carname="Volvo";

    In computer programs, variables are often declared without a value. The value can be something that has to be calculated, or something that will be provided later, like user input. Variable declared without a value will have the value undefined.

    The variable carname will have the value undefined after the execution of the following statement: var carname;

    var hoisting

    In JavaScript, a variable can be declared after being used.

     bla = 2
     var bla;
      // ...
    
      // is implicitly understood as:
    
     var bla;
     bla = 2;
    

    For that reason, it is recommended to always declare variable at the top of functions. Otherwise, it may lead to confusing cases

    When declaring a variable without assigning a value to it, there still needs to be some memory available for it, otherwise you cannot make a reference to the variable later in the program. I don't think it's a noticeable amount of memory being used and won't make a difference.

提交回复
热议问题