Why Do We Need to Declare Variables with var, let, or const?

4 min read |

let-const-var

What Are Undeclared Variables in JavaScript and Why Don't We Use Them Often?

An undeclared variable is a variable that is not declared using one of the keywords var, let, or const. Syntax:

// In JavaScript, we normally declare and assign a value to our variables like this:

var num = 10;

// When we do this, JavaScript is actually doing `var num;` first and then `num = 10` on execution. In JavaScript, this is handled by the concept called `hoisting`.

// We can also create a variable without `var`, `let`, or `const` keywords like this:

undeclaredVariable = "value";

In JavaScript, an undeclared variable does not exist until we assign it a value (they are not hoisted, unlike declared variables). Therefore, assigning a value to an undeclared variable implicitly creates it as a global variable when the assignment is executed. This means all undeclared variables are global variables. (This is also highly likely to mess up the global objects in both browser and back-end environments.)

To demonstrate this behavior, let's look at this example:

function example() {
  isGlobal = true;

  let isLocal = true;
}

example();
/**
 * Now that we have executed the example function, JavaScript
 * will create the `isGlobal` variable as a global variable. Let's check this:

console.log(isGlobal);

/**

* Output: true

*/

console.log(isLocal);

/**
 Output: ReferenceError: isLocal is not defined
 Reason: this is a totally expected behavior b/c a declared variable will be first hoisted at either function scope or global scope before function
 execution, more on this later.
 */

Now that we understand how JavaScript handles undeclared variables, it's always recommended to use declared variables in a function or global scope. Let's move on to understand declared variables in depth.

var

Before ES6, var was the only keyword available to create a variable. The scope of a variable declared with this keyword is its current execution context. This is either the enclosing function or, for variables declared outside any function, the global context.

Example:

// Global Scope:

console.log(varExample);

/* Output: undefined, the variable is hoisted to the top before execution
therefore it doesn't throw ReferenceError and in JavaScript, variables declared with
var will be initialized with undefined as value (this is not the case for let and const)
*/

var varExample = "value";

// Function Scope:

function example() {
  console.log(isLocal);

  var isLocal = true;

  if (isLocal) {
    var funScoped = true;
  }

  console.log(funScoped); // Output: true, why?
}

example();

/**
Output: true
That's right, the variable is hoisted to the top of the
function scope before execution. This kind of behavior makes it
hard to debug, so it's always recommended to declare and initialize
your variables at the top of the context before using them.
*/

let

The major upgrade from var to let in ES6 is that let is block scoped, not function scoped. What does this mean? It means the variable's scope is bound to the block in which it was declared, not the function. Example? Sure:

//Block scope:

function example() {
  // let's use the above example

  let isLocal = true;

  if (isLocal) {
    // A variable declared with let or const will have block scope context, i.e., the context in this condition
    // is bound to this block only, not to the function.

    let funScoped = false;
  }

  console.log(funScoped);

  /**
   * Output: ReferenceError: funScoped is not defined
   * Reason: This is a totally expected behavior because a variable declared with let is block scoped and not accessible outside the block.
   */
}

console.log(name);
let name = "daniel";

/*
Output: ReferenceError: Cannot access 'name' before initialization
This is because JavaScript will hoist variables declared with both
`const` and `let`, but they will remain uninitialized.
*/

The two most noticeable differences between let and const are:

One final example:


const NAME;
console.log(NAME); // Output: SyntaxError: Missing initializer in const declaration
NAME = "daniel";

const X = 'x';
X = 'y';  // Output: TypeError: Assignment to constant variable.

I hope you found something useful in this post. If you have a few more minutes, read another post 🤖

Thank you for reading!