Yogesh Chauhan's Blog

Function Scope in JavaScript for Beginners

in JavaScript on March 21, 2020

There are two types of scope in JavaScript.

Local scope

Global scope

Also, JavaScript has function scope. Each function creates a new scope.

Scope determines the accessibility of variables. Variables defined inside a function are not accessible from outside the function.

Local Scope Variables

Variables declared within a function become local to the function. So they have have Function scope. They can only be accessed from within the function.

For example,

As we can see in the example above, if we try to access the variable outside of the function scope then it will raise undefined error.

Local variables are only recognized inside functions so variables with the same name can be used in different functions.

In other words, local variables are created when a function starts, and deleted when the function is completed.

Global Scope Variables

A variable is global if its declared outside a function.

All scripts and functions on a web page can access the global variables.

For example,

As we can see in the example above, we can easily access the global variable inside the function.

Can Variables become Global Automatically?

If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.

For example,

As we can see in the example above, we can easily access the variable outside of the function.

NOTE: In “Strict Mode”, undeclared variables are not automatically global. I will talk more about Strict Mode in future blog post.


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
How to obfuscate JavaScript code to hide it from View Source?JavaScriptSQL ALL OperatorSQL/MySQLHow to create a Progress Bar using JavaScript?JavaScriptHow to add today’s date in HTML input date value using JavaScript?JavaScriptAn Example of Cross-site Scripting (XSS) Attack in PHP and How to Avoid It?PHPThe Difference Between the echo and print Commands in PHPPHP