Skip to main content

📟 Variable Declaration

Useful resources:

var

Scope of var

var declarations are global or function scope.

Global Scope

The scope is global when var variable is declared outside of a function.

Global Scope
var myVar = "Global Variable";
console.log(myVar); // Global Variable
console.log(window.myVar); // Global Variable

Function Scope

The scope is function scope when var variable is declared inside a function. This means that it is only available within that function.

Function Scope

Re-declared and Updated

Re-declaration?

var variable can be re-declared and updated

note

A repeated var declaration of the same identifier name in a scope is effectively a do-nothing operation.

repeated var
After 'pre-process' repeated var
var studentName;
var studentName; // pointless, no-op

studentName = "Frank";
console.log(studentName);
// Frank

console.log(studentName); // Frank

Hoisting of var

Hoisting: Yet Another Metaphor

It is useful to think of hoisting as a series of actions JS takes in setting up the program before execution.

  1. The identifier is hoisted to the top of the scope
  2. It's automatically initialized to the value undefined. So that the variable can be used throughout the entire scope.
Before 'pre-process'
age = 20;
console.log(age);
// 20
var age = 30;
After 'pre-process'
var age; // hoisted declaration

age = 20;
console.log(age);
age = 30;
info

However, function declarations are entirely hoisted to the top of each scope. And they are hoisted first, then variables are hoisted immediately after all the functions.

Before 'pre-process'
age = 20;
sayAge(); // age is 20

function sayAge() {
console.log(`age is ${age}`);
}
var age;
After 'pre-process'
function sayAge() {
console.log(`age is ${age}`);
}
var age;

age = 20;
sayAge(); // age is 20

Questions

Functions are hoisted entirely

hoisting