Variable scope

Coding with JavaScript

🕑 This lesson will take about 10 minutes

Variable scope refers to the context that a variable is defined in. JavaScript has two variable scopes: global and local.

  • A global variable is a variable that is declared outside a function and its value can be accessed and modified anywhere in your program

  • A local variable is a variable that is declared inside a function definition. It is created and then destroyed every time the function runs, and cannot be accessed or modified from outside the function.

This video explains variable scope when using functions and how to declare and use local and global variables in your JavaScript programs.

Sample HTML and CSS code

The sample code below demonstrates how to use local and global variables in JavaScript. Open the codepen snippet in a new tab/window and click Console to view the output of any console.log() messages (including the error message when attempting to access a local variable outside a function).

Next lesson: Arrays