Denny Chang
Contact
  • Theme Mode

  • Language

[JS fundamental] Variable Declaration
[JS fundamental] Variable Declarationthe image is from unsplash

Today's topic: Varaible Declaration

Basically, there three ways to declare a variable var let and const and the difference between them are :

var let const
Scope function scopr/global scope block scope block scope
re-assign can re-assign can re-assign can NOT re-assign
hoist Hoist Hoist, but go to TDZ first Hoist, but go to TDZ first

*TDZ = Temporal Dead Zone

Some Explanations

Scope

means that,where are the variable declaration is working simply speaking, you can get the value of this variable in this scope, but outside of this scope you can not access them.

// function scope

function here() {
  var a = 5;
}
here();
console.log(a); // you got a is not defined

// block scope

/*
a block scope is { } these curly brackets
*/

if (true) {
  let a = 5;
}
console.log(a); // you got a is not defined
Hoist and TDZ

Simply speaking, when declaring variable the declaration will be hoisted, and assing value will not Hoist, you can think it is like to move the declaration to the top

the keyword Var, when hoisting happen, it will initalize the value as undefined first.

And declaration key: let and const They do hoisting, too. But they are not going to initialize the varaible as undefined, the variables go to Temporal Dead Zone first. Until code goes to the declaration line, it will be assign value, then you can access the variable

// 範例:

console.log(a); // you got undefined
var a = 6;

console.log(b); // you got ReferenceError: b is not defined (in browser)
// ReferenceError: Cannot access 'a' before initialization。 (in node)
let b = 6;

// hoist to declaration, the Temporal Dead Zone

console.log(b); //

let b;
/*
1. let b hoisting to the top: in TDZ
2. pregram goes to console.log(b) : Cannot access 'b'
3.pregram goes to let b: assign undefined to b , and leave TDZ
*/

Some simple concept about variable declaration Recording it .

this is today's sharing 👋