JavaScript Variables, Scope, and Hoisting – A Beginner’s Guide

Telegram Group Join Now
WhatsApp Group Join Now

Hi everyone! I’m Rupnath, and in this post, I’ll go over three fundamental JavaScript variable principles that all beginners should understand: variable declaration, scope, and hoisting. Knowing these subjects will assist you in writing cleaner code and avoiding common problems. Now let’s get started.

What Are Variables in JavaScript?

Variables are essentially named containers that store data in our code. They enable us to label and reference pieces of data in our programs.

In JavaScript, we can declare a variable using the keywords var, let, or const like so:

var myVariable;
let myVariable; 
const myVariable;

This allocates memory for that variable and allows us to assign a value to it later:

var myNumber = 10;

Now myNumber contains the data value 10 that we can use in our code.

Writing reusable code requires the use of variables. In order to identify the type of data we are working with, we give variables names that are meaningful.

Variable Scope in JavaScript

The scope of a variable determines where in our code it is available to use. JavaScript has two types of scope:

Global Scope

A variable declared outside of any function or code block has global scope. This means it can be accessed and altered from anywhere in our code:

var globalVariable = "I'm global!"; 

function myFunction() {
  console.log(globalVariable); <em>// I can access it here!</em>
}

console.log(globalVariable); <em>// And here!</em>

Global variables are useful for values we need everywhere. But we should minimize using them as they can lead to naming collisions and unintended side effects.

Local Scope

A variable declared inside a function or code block with {} has local scope:

function myFunction() {

  var localVariable = "I'm local!";
  
  console.log(localVariable); <em>// Accessible here</em>
  
}

console.log(localVariable); <em>// Error! Can't be accessed outside the function</em>

Local variables only exist within the function or block they are declared in.

Local scope is extremely useful as it allows us to declare variables that won’t accidentally overwrite values in other parts of our code. It also frees us from having to worry about naming collisions with other functions or code blocks.

Hoisting in JavaScript

Declarations for variables and functions are “hoisted” to the top of their enclosing scope because of the way the browser interprets and executes JavaScript.

This means variable and function declarations are processed before any code is executed. Hoisting allows us to access a function or variable declaration before it appears in code:

console.log(myVariable); <em>// undefined</em>

var myVariable = "Hello!";

Even though myVariable is declared after we use it, we are able to access it due to hoisting. But the assignment of “Hello!” to myVariable is not hoisted.

Same with functions:

myFunction(); <em>// Works!</em>

function myFunction() {
  console.log("Hi from myFunction!");
}

Function declarations are hoisted, so we can call myFunction() before declaring it. But again function assignments are not hoisted:

myOtherFunction(); <em>// Error!</em>

var myOtherFunction = function() {
  console.log("Hi!");
}

Since myOtherFunction is declared with a variable assignment, it doesn’t get hoisted.

Why Understanding Scope and Hoisting Matters

  • Avoid unintended overwriting of variable values due to scope issues
  • Prevent naming collisions or ambiguity with local variables
  • Write cleaner code by declaring variables where they are used
  • Call functions before having to declare them
  • Avoid bugs caused by out-of-order code execution

Thinking about scope and hoisting leads to more modular, legible code!

Variable Declaration Keywords: var vs let vs const

JavaScript provides three main keywords for declaring variables, each with their own nuances:

var

  • Function scoped
  • Hoisted
  • Can be redeclared and updated
var myVar = "Hello!";
var myVar = "Goodbye!"; <em>// Allowed!</em>
  • Should be avoided in ES6 in favor of let and const

let

  • Block scoped
  • Hoisted but not initialized until declaration
  • Can be updated but not redeclared
let myLet = "Hello!";
myLet = "Goodbye!"; <em>// Allowed!</em>
let myLet = "Hi"; <em>// Error!</em>
  • Preferred for local variable declarations in modern code

const

  • Block scoped
  • Must be initialized at declaration
  • Cannot be redeclared or updated
const myConst = "Hello!";
myConst = "Goodbye!"; <em>// Error!</em>
const myConst = "Hi"; <em>// Error!</em>
  • Use for variables that should never change

Understanding the nuances of these keywords will help you avoid errors and write cleaner code.

Variable Naming Tips

  • Use descriptive, unambiguous names like totalAmount or getUserInfo.
  • Avoid single-letter variables like a or abbreviated names that can be unclear like usrNm.
  • Names with multiple words like firstName can use camelCase.
  • Constants can be named in all uppercase with underscores like MAX_USERS.
  • Avoid reserved keywords like var or function.

Managing Scope Effectively

  • Declare variables in the smallest scope needed. Avoid globals.
  • Declare functions before calling them to avoid issues with hoisting.
  • Be careful of scoping issues when nesting functions and blocks.
  • Use let and const for block-scoped declarations rather than var.
JavaScript Variables, Scope, and Hoisting

Common Pitfalls to Avoid

  • Accidentally using a variable before it is declared and causing a ReferenceError.
  • Forgetting to declare a variable with var/let/const and unintentionally making it global.
  • Declaring multiple local variables with the same name in nested functions leads to collisions.
  • Attempting to reassign or redeclare const variables.
  • Forgetting function declarations are hoisted and calling them before declaring.

In Summary

  • JavaScript variables provide labeled data storage to use in our code.
  • Scope determines where a variable is accessible – either globally or locally.
  • Hoisting allows variable and function declarations to be used before they appear in code.
  • Using var, let and const properly avoids issues like redeclaration and unintended globals.
  • Good naming conventions and scoping make code more readable.
  • Be mindful of hoisting, scope, and pitfalls to become a better JavaScript developer.

I hope these explanations and examples have helped demystify some core concepts around variables in JavaScript. Let me know in the comments if you have any other questions.

Leave a comment