
- 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
What is the difference between global and local Variables in JavaScript?
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.
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
Here’s how you can declare a global variable
<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
- What is the difference between global and local variables in Python?
- What are local variables and global variables in C++?
- Difference Between Local and Global Variable
- What is the difference between Local Events and Global Events in jQuery?
- Global and Local Variables in C#
- Global and Local Variables in Python?
- Global and Local Variables in Java
- Global vs Local variables in Python
- Difference between static, auto, global and local variable in C++
- What is the difference between class variables and instance variables in Java?
- How are C++ Local and Global variables initialized by default?
- What is the difference between dynamic type variables and object type variables?
- What is the correct way to define global variables in JavaScript?
- What is the difference between local storage vs cookies?
- What is the difference between == and === in JavaScript?
Advertisements