- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 correct way to define global variables in JavaScript?
A global variable has global scope which means it can be defined anywhere in your JavaScript code.
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.
Commonly, a global variable is declared like the following −
<html> <body onload = checkscope();> <script> <!-- var myVar = "global"; // Declare a global variable function checkscope() { document.write(myVar); } //--> </script> </body> </html>
But, what you can above is the traditional method of using global variables. The best practice is to use it like the following with “window” −
<html> <body onload = checkscope();> <script> window.myVar = "global"; // Declare a global variable function checkscope( ) { alert(myVar); } </script> </body> </html>
Advertisements