Scope of variables in JavaScript

What is the scope of variables in Javascript?

Scope in javascript refers to the variables and the functions which are accessible and in what context it will be executed. There are basically 2 types of scope which I would discuss in this article.

Global Scope Variables

Global variables are usually declared at the top level and it will be accessible anywhere in the code.

var category = "Javascript Blog"; // global scope variable. All the methods will be able to access this variable.

function ReadBlogLine() {
 return alert(category);

Local Scope Variables

Local variables in Javascript are limited to certain part of the code or method. Hence, only the method will be able to access the variables.

function ReadBlogLine() {
var myLocalVariable="Hello World";
 return alert(myLocalVariable);
alert(myLocalVariable);// Throws an error because the scope is local to the method here.

Let us take a look at javascript scope of variables in nested functions
In the below example you can see the variable name is declared in the animal function and it is also accessible in the animal count function and JoinAnimalNames function. The variable will be accessible easily inside the nested functions. The variable namesLength is a local scope to animalsCount method and this will not be accessible in any other methods.

function animals () {
	var names = ["CAT", "DOG", "RABBIT"];
	function animalsCount () {
		var namesLength= animals.length;
		return namesLength;
	function JoinAnimalNames() {
		return "I have " + animalsCount() + " Pets at home:\n\n" + names.join("\n");
	return JoinAnimalNames(); 
alert(animals ()); // I have 3 Pets at home CAT DOG RABBIT
Leave a Reply

Your email address will not be published. Required fields are marked *

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like