

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How does JavaScript Variable Scope work?
The scope of a variable is the region of your program in which it is defined. JavaScript variables have only two scopes.
- Global Variables − A global variable has a global scope which means it can be defined anywhere in your JavaScript code.
- Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.
Let’s see how the scope of variables works in JavaScript.
Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable.
Example
<html> <body onload = checkscope();> <script> <!-- var myVar = "global"; // Declare a global variable function checkscope( ) { var myVar = "local"; // Declare a local variable document.write(myVar); } //--> </script> </body> </html>
- Related Questions & Answers
- Define Variable Scope in JavaScript?
- Does JavaScript support block scope?
- How does variable scopes work in Python Modules?
- How does JavaScript .prototype work?
- PHP Variable Scope
- How does recursion function work in JavaScript?
- How does Exceptions Handling work in JavaScript?
- How does asynchronous code work in JavaScript?
- How does JavaScript work behind the scene?
- How variable scope works in Python function?
- How does JavaScript 'return' statement work?
- How does jQuery.scrollTop() work?
- How does jQuery.scrollLeft() work?
- How does backpropagation work?
- How does classification work?
Advertisements