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.

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.

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.

You may also like...

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.