- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company

Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Define a global variable in a JavaScript function
Is it possible to define a global variable in a JavaScript function?
I want use the trailimage variable (declared in the makeObj function) in other functions.
- declaration

- 27 to declare a global simply don't use the "var" keyword – Ibu Apr 26, 2011 at 6:46
- 26 @Ibrahim: "to declare a global simply don't use the "var" keyword" Gak! The Horror ! ;-) Thankfully, strict mode does away with implicit globals. – T.J. Crowder Apr 26, 2011 at 7:22
- 35 @Ibrahim Diallo - not using var doesn't declare a global variable. A consequence of assigning a value to an undeclared variable is the creation of a property on the global object, which is quite different to declaring a variable. – RobG Apr 26, 2011 at 7:34
- 3 useful info in this answer, too stackoverflow.com/a/4862268/1356098 :) – Erenor Paz Nov 26, 2012 at 15:35
17 Answers 17
As the others have said, you can use var at global scope (outside of all functions and modules) to declare a global variable:
(Note that that's only true at global scope. If that code were in a module — <script type="module">...</script> — it wouldn't be at global scope, so that wouldn't create a global.)
Alternatively:
In modern environments, you can assign to a property on the object that globalThis refers to ( globalThis was added in ES2020):
On browsers, you can do the same thing with the global called window :
...because in browsers, all global variables global variables declared with var are properties of the window object. (The new let , const , and class statements [added in ES2015] at global scope create globals that aren't properties of the global object; a new concept in ES2015.)
(There's also the horror of implicit globals , but don't do it on purpose and do your best to avoid doing it by accident, perhaps by using ES5's "use strict" .)
All that said: I'd avoid global variables if you possibly can (and you almost certainly can). As I mentioned, they end up being properties of window , and window is already plenty crowded enough what with all elements with an id (and many with just a name ) being dumped in it (and regardless that upcoming specification, IE dumps just about anything with a name on there).
Instead, in modern environments, use modules:
The top level code in a module is at module scope, not global scope, so that creates a variable that all of the code in that module can see, but that isn't global.
In obsolete environments without module support, wrap your code in a scoping function and use variables local to that scoping function, and make your other functions closures within it:

- 11 Note that using window won't work in Node. The easiest trick here is to set: GLOBAL.window = GLOBAL; -- as explained in this related question . Of course, it's not pretty conceptually. I prefer to do things the other way around, so I can use GLOBAL instead of window . – Domi Apr 5, 2014 at 21:58
- 4 @CasparKleijne, I don't understand it. Why would you assign it on window when you literally have no evidence that the window object actually exists. You know nothing about how your code will be used in the future. It might be even used in the MongoDB environment or rino instead of your node. And the window object is also not visible even in the browser if you use web workers for instance. This will completely kill reusability. – Gherman Feb 10, 2016 at 11:36
- 6 window.yourGlobalVariable = ...; works like a charm after reading 5 to 6 questions on stack site. – Ahmed Syed Feb 16, 2016 at 12:25
- 6 @JacquesKoekemoer: There's no reason whatsoever to use eval there. Instead: window[dynamic_variable_name] = dynamic_variable_value; – T.J. Crowder Mar 10, 2016 at 10:05
- 1 @AstritSpanca - That's the Horror of Implicit Globals I mention in a parenthetical in the middle of the answer. :-) – T.J. Crowder Feb 20, 2020 at 9:16
Just declare
outside. Then
If you read the comments there's a nice discussion around this particular naming convention.
It seems that since my answer has been posted the naming convention has gotten more formal. People who teach, write books, etc. speak about var declaration, and function declaration.
Here is the additional Wikipedia post that supports my point: Declarations and definitions ...and to answer the main question. Declare variable before your function. This will work and it will comply to the good practice of declaring your variables at the top of the scope :)

- 7 If You want to define your variables elsewhere be sure to understand what hoisting is. Here is a very nice article about it adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting . Good luck! – op1ekun Dec 29, 2012 at 10:55
- 1 This isn't what definition and declaration mean in C. Your first line could be either a declaration or a definition (depending on where it is); the second is just an assignment. A declaration just specifies the interpretation of the identifier (ie. myVar is an int ); if the declaration also reserves storage, it is a definition . This is unrelated to typing; it's part of how compilation units understand references to other compilation units. – EML Jul 26, 2014 at 11:20
- 4 Even in JS, var myVar is called declaration (it doesn't need to be typed) and myVar = 10 an assignment . I've heard the term "defintion" for the compound ( var myVar = 10; ). – Bergi Aug 11, 2014 at 14:17
- 2 This doesn't help to answer the question. It should have been a comment, not an answer. – Stuntddude Mar 7, 2016 at 17:32
- 2 @Stuntddude you're probably right :( I started answering the question and then decided to diverge a bit, and well this is what we've got. Still some ppl still find it useful so I've left it here. Thanks for your feedback! – op1ekun Mar 8, 2016 at 9:20
Just declare it outside the functions, and assign values inside the functions. Something like:
Or simply removing "var" from your variable name inside function also makes it global, but it is better to declare it outside once for cleaner code. This will also work:
I hope this example explains more: http://jsfiddle.net/qCrGE/

- Pretty clean and working solution +1 – Robert Sep 18, 2021 at 6:48
No, you can't. Just declare the variable outside the function. You don't have to declare it at the same time as you assign the value:
- 1 Sorry! "Is it possible to define a global variable in a JavaScript function?" -- "No, you can't" isn't correct, as the first answer shows! – mustafa.0x Nov 17, 2013 at 7:29
- 6 @mustafa.0x: You are mistaken. You can't define a global variable inside a function. You can implicitly create a global variable, or create a window property inside a function, but you can't define a global variable inside a function. – Guffa Nov 17, 2013 at 13:22
- 1 With regards to JavaScript in a browser environment, a global variable and a property of window are synonymous. Either way, the semantic distinction you're making is clear, so I don't mind un-downvoting. Edit: unable to change my vote, sorry! – mustafa.0x Nov 18, 2013 at 19:05
- 2 if you're not using strict (but why aren't you using strict?), you actually can declare and define global vars inside a function by going against all good practices and just not using the var , which is what Guffa meant by implicitly create (such as @DhruvPathak pointed there, as well). – cregox Feb 25, 2017 at 12:48
There are three types of scope in JavaScript:
- Global Scope: where the variable is available through the code.
- Block Scope: where the variable is available inside a certain area like a function.
- Local Scope: where the variable is available in more certain areas, like an if -statement
If you add Var before the variable name, then its scope is determined where its location is

It depends on what you intend by the word "global". If you want global scope on a variable for function use (which is what the OP wants) then you should read after the edit. If you want to reuse data from page to page without the use of a server, you should be looking to you use sessionStorage .
Session Storage
I realize there is probably a lot of syntax errors in this but its the general idea... Thanks so much LayZee for pointing this out... You can find what a local and session Storage is at http://www.w3schools.com/html/html5_webstorage.asp . I have needed the same thing for my code and this was a really good idea.
As of (I believe) 2015, a new "standard" for javascript (if you will) was introduced. This standard introduced many new ideas into javascript, one of them being the implementation of scope.
https://www.w3schools.com/js/js_scope.asp has all the details concerning this idea, but the cliff notes:
const defines a constant.
var has "global" scope.
let has "function" or "block" scope.
- So far this is the only answer that works at all, but it requires reloading the page and location.reload(false); refreshes the page repeatedly. – iyrin Jun 25, 2018 at 6:46
- In my case I replace sessionStorage with localStorage and this suppress the need to function LocalToGlobalVariable() . I am using localStorage.setItem("xxx", "yyy") and localStorage.getItem("xxx") for setting and getting the variables. – Ozgun Senyuva Jan 8, 2022 at 19:31
Classic example:
A modern, safe example following best practice by using an IIFE :
Nowadays, there's also the option of using the WebStorage API :
Performance-wise, I'm not sure whether it is noticeably slower than storing values in variables.
Widespread browser support as stated on Can I use... .
- localStorage and sessionStorage only works for string values. – HereToLearn_ Oct 21, 2015 at 17:10
- That is right, @HereToLearn_, but then you can use localStorage.foo = JSON.stringify({ arbitrary: 'object', meaning: 42, awesome: true }); and var foo = JSON.decode(localStorage.foo); . – Lars Gyrup Brink Nielsen Oct 26, 2015 at 19:54
- What localStorage has to do with global variables? – Michał Perłakowski Jan 16, 2016 at 2:52
- 2 OP is looking for at solution to this problem: "I want use the trailimage variable (declared in the makeObj function) in other functions." Who says that the solution has to involve global variables? Global variables are seldom a good solution to anything. – Lars Gyrup Brink Nielsen Jan 17, 2016 at 10:01
It is very simple. Define the trailimage variable outside the function and set its value in the makeObj function. Now you can access its value from anywhere.
- I was expecting this to work, but it didn't..? trailimage was only available as a global entity when not defined anywhere - with or without var . – Johan Feb 7 at 10:13
Yes, You can. Just don't use var, don't use let. Just initialize variable and it will be automaticly assigned global:

Global variables are declared outside of a function for accessibility throughout the program, while local variables are stored within a function using var for use only within that function’s scope. If you declare a variable without using var, even if it’s inside a function, it will still be seen as global. References = https://www.freecodecamp.org/news/global-variables-in-javascript-explained/
All variables declared without "var" or "let" or anything else preceding it like "const" are global. So ....
As an alternative to global vars, you may use the localstorage of browsers (if not using older versions). You can use upto 5MB of this storage. The code would be
and this can be retrieved any time, even after you leave and open it at another time.
Hope this would help you !

If you are making a startup function, you can define global functions and variables this way:
Because the function is invoked globally with this argument, this is global scope here. So, the something should be a global thing.
- this is undefined in strict mode outside a function and should not be used to refer to the global object. – Michał Perłakowski Jan 16, 2016 at 2:51
Here is sample code that might can be helpful.
Here I found a nice answer: How can one declare a global variable in JavaScript?
- 1 Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference. – Rohit Gupta Jul 24, 2015 at 5:39
To use the window object is not a good idea. As I see in comments,
This will throw an error to use the say_hello variable we need to first call the showMessage function .

Here is another easy method to make the variable available in other functions without having to use global variables:
function makeObj() { // var trailimage = 'test'; makeObj.trailimage = 'test'; } function someOtherFunction() { document.write(makeObj.trailimage); } makeObj(); someOtherFunction();
Not the answer you're looking for? Browse other questions tagged javascript function variables scope declaration or ask your own question .
- The Overflow Blog
- How Intuit democratizes AI development across teams through reusability sponsored post
- The nature of simulating nature: A Q&A with IBM Quantum researcher Dr. Jamie...
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- Launching the CI/CD and R Collectives and community editing features for...
- The [amazon] tag is being burninated
- Temporary policy: ChatGPT is banned
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
Hot Network Questions
- How can we prove that the supernatural or paranormal doesn't exist?
- Knocking Out Zombies
- Linear regulator thermal information missing in datasheet
- How do/should administrators estimate the cost of producing an online introductory mathematics class?
- Isolate page to turn off header
- How to Fix my DIY Smart Switch Install
- Did this satellite streak past the Hubble Space Telescope so close that it was out of focus? If so, how close was it?
- Will Gnome 43 be included in the upgrades of 22.04 Jammy?
- Showing the difference between two models with similar AUC-ROC curves
- Doesn't analytically integrate sensibly let alone correctly
- Why do small African island nations perform better than African continental nations, considering democracy and human development?
- Tips for golfing in SVG
- "Is" or "are" for two uncountable words?
- What is \newluafunction? How can I use it?
- Relation between transaction data and transaction id
- nicematrix: controlling column spaces
- Why does it seem like I am losing IP addresses after subnetting with the subnet mask of 255.255.255.192/26?
- Counting Letters in a String
- Precise control of fraction expression
- Linear Algebra - Linear transformation question
- Why did Ukraine abstain from the UNHRC vote on China?
- Is there a single-word adjective for "having exceptionally strong moral principles"?
- What is the difference between paper presentation and poster presentation?
- Largest Binary Area
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .
- Data Structure & Algorithm Classes (Live)
- System Design (Live)
- DevOps(Live)
- Explore More Live Courses
- Interview Preparation Course
- Data Science (Live)
- GATE CS & IT 2024
- Data Structure & Algorithm-Self Paced(C++/JAVA)
- Data Structures & Algorithms in Python
- Explore More Self-Paced Courses
- C++ Programming - Beginner to Advanced
- Java Programming - Beginner to Advanced
- C Programming - Beginner to Advanced
- Android App Development with Kotlin(Live)
- Full Stack Development with React & Node JS(Live)
- Java Backend Development(Live)
- React JS (Basic to Advanced)
- JavaScript Foundation
- Complete Data Science Program(Live)
- Mastering Data Analytics
- CBSE Class 12 Computer Science
- School Guide
- All Courses
- Linked List
- Binary Tree
- Binary Search Tree
- Advanced Data Structure
- All Data Structures
- Asymptotic Analysis
- Worst, Average and Best Cases
- Asymptotic Notations
- Little o and little omega notations
- Lower and Upper Bound Theory
- Analysis of Loops
- Solving Recurrences
- Amortized Analysis
- What does 'Space Complexity' mean ?
- Pseudo-polynomial Algorithms
- Polynomial Time Approximation Scheme
- A Time Complexity Question
- Searching Algorithms
- Sorting Algorithms
- Graph Algorithms
- Pattern Searching
- Geometric Algorithms
- Mathematical
- Bitwise Algorithms
- Randomized Algorithms
- Greedy Algorithms
- Dynamic Programming
- Divide and Conquer
- Backtracking
- Branch and Bound
- All Algorithms
- Company Preparation
- Practice Company Questions
- Interview Experiences
- Experienced Interviews
- Internship Interviews
- Competitive Programming
- Design Patterns
- System Design Tutorial
- Multiple Choice Quizzes
- Go Language
- Tailwind CSS
- Foundation CSS
- Materialize CSS
- Semantic UI
- Angular PrimeNG
- Angular ngx Bootstrap
- jQuery Mobile
- jQuery EasyUI
- React Bootstrap
- React Rebass
- React Desktop
- React Suite
- ReactJS Evergreen
- ReactJS Reactstrap
- BlueprintJS
- TensorFlow.js
- English Grammar
- School Programming
- Number System
- Trigonometry
- Probability
- Mensuration
- Class 8 Syllabus
- Class 9 Syllabus
- Class 10 Syllabus
- Class 8 Notes
- Class 9 Notes
- Class 10 Notes
- Class 11 Notes
- Class 12 Notes
- Class 8 Maths Solution
- Class 9 Maths Solution
- Class 10 Maths Solution
- Class 11 Maths Solution
- Class 12 Maths Solution
- Class 7 Notes
- History Class 7
- History Class 8
- History Class 9
- Geo. Class 7
- Geo. Class 8
- Geo. Class 9
- Civics Class 7
- Civics Class 8
- Business Studies (Class 11th)
- Microeconomics (Class 11th)
- Statistics for Economics (Class 11th)
- Business Studies (Class 12th)
- Accountancy (Class 12th)
- Macroeconomics (Class 12th)
- Machine Learning
- Data Science
- Mathematics
- Operating System
- Computer Networks
- Computer Organization and Architecture
- Theory of Computation
- Compiler Design
- Digital Logic
- Software Engineering
- GATE 2024 Live Course
- GATE Computer Science Notes
- Last Minute Notes
- GATE CS Solved Papers
- GATE CS Original Papers and Official Keys
- GATE CS 2023 Syllabus
- Important Topics for GATE CS
- GATE 2023 Important Dates
- Software Design Patterns
- HTML Cheat Sheet
- CSS Cheat Sheet
- Bootstrap Cheat Sheet
- JS Cheat Sheet
- jQuery Cheat Sheet
- Angular Cheat Sheet
- Facebook SDE Sheet
- Amazon SDE Sheet
- Apple SDE Sheet
- Netflix SDE Sheet
- Google SDE Sheet
- Wipro Coding Sheet
- Infosys Coding Sheet
- TCS Coding Sheet
- Cognizant Coding Sheet
- HCL Coding Sheet
- FAANG Coding Sheet
- Love Babbar Sheet
- Mass Recruiter Sheet
- Product-Based Coding Sheet
- Company-Wise Preparation Sheet
- Array Sheet
- String Sheet
- Graph Sheet
- ISRO CS Original Papers and Official Keys
- ISRO CS Solved Papers
- ISRO CS Syllabus for Scientist/Engineer Exam
- UGC NET CS Notes Paper II
- UGC NET CS Notes Paper III
- UGC NET CS Solved Papers
- Campus Ambassador Program
- School Ambassador Program
- Geek of the Month
- Campus Geek of the Month
- Placement Course
- Testimonials
- Student Chapter
- Geek on the Top
- Geography Notes
- History Notes
- Science & Tech. Notes
- Ethics Notes
- Polity Notes
- Economics Notes
- UPSC Previous Year Papers
- SSC CGL Syllabus
- General Studies
- Subjectwise Practice Papers
- Previous Year Papers
- SBI Clerk Syllabus
- General Awareness
- Quantitative Aptitude
- Reasoning Ability
- SBI Clerk Practice Papers
- SBI PO Syllabus
- SBI PO Practice Papers
- IBPS PO 2022 Syllabus
- English Notes
- Reasoning Notes
- Mock Question Papers
- IBPS Clerk Syllabus
- Apply for a Job
- Apply through Jobathon
- Hire through Jobathon
- All DSA Problems
- Problem of the Day
- GFG SDE Sheet
- Top 50 Array Problems
- Top 50 String Problems
- Top 50 Tree Problems
- Top 50 Graph Problems
- Top 50 DP Problems
- Solving For India-Hackthon
- GFG Weekly Coding Contest
- Job-A-Thon: Hiring Challenge
- BiWizard School Contest
- All Contests and Events
- Saved Videos
- What's New ?
- JS-Function
- JS-Generator
- JS-Expressions
- JS-ArrayBuffer
- JS-Tutorial
- Web Development
- Web-Technology
Related Articles
- Write Articles
- Pick Topics to write
- Guidelines to Write
- Get Technical Writing Internship
- Write an Interview Experience
- JavaScript Examples
- How to iterate over a callback n times in JavaScript ?
- How to negate a predicate function in JavaScript ?
- How to make a word count in textarea using JavaScript ?
- How to add fade-out effect using pure JavaScript ?
- How to add fade-in effect using pure JavaScript ?
- How to implement a function that enable another function after specified time using JavaScript ?
- Using the function* Declaration in JavaScript
- How to override a JavaScript function ?
How to change the value of a global variable inside of a function using JavaScript ?
- How to wait for a promise to finish before returning the variable of a function ?
- How to include a JavaScript file in another JavaScript file ?
- How to get the javascript function parameter names/values dynamically ?
- Passing a function as a parameter in JavaScript
- How to create a function that invokes each provided function with the arguments it receives using JavaScript ?
- How to convert two-dimensional array into an object in JavaScript ?
- How to create an object from two arrays in JavaScript?
- How to use array that include and check an object against a property of an object ?
- How to print object by id in an array of objects in JavaScript ?
- How to implement a filter() for Objects in JavaScript ?
- How to get all the methods of an object using JavaScript ?
- How to convert an Object {} to an Array [] of key-value pairs in JavaScript?
- How to iterate over a JavaScript object ?
- How to add an object to an array in JavaScript ?
- How to remove Objects from Associative Array in JavaScript ?
- How to get a key in a JavaScript object by its value ?
- How to push an array into the object in JavaScript ?
- How to get a subset of a javascript object’s properties?
- How to remove a property from JavaScript object ?
- How to add float numbers using JavaScript ?
- Currency Converter in JavaScript
- How to get median of an array of numbers in JavaScript ?
- Round off a number to the next multiple of 5 using JavaScript
- Convert a negative number to positive in JavaScript
- Find quotient and remainder by dividing an integer in JavaScript
- How to flatten a given array up to the specified depth in JavaScript ?
- How to get the standard deviation of an array of numbers using JavaScript ?
- How to evaluate binomial coefficient of two integers n and k in JavaScript ?
- How to calculate greatest common divisor of two or more numbers/arrays in JavaScript ?
- How to test a value x against predicate function and returns fn(x) or x in JavaScript ?
- How to check two numbers are approximately equal in JavaScript ?
- How to create slider to map a range of values in JavaScript ?
- RMS Value Of Array in JavaScript
- JavaScript to generate random hex codes of color
- How to get removed elements of a given array until the passed function returns true in JavaScript ?
- How to filter values from an array for which the comparator function does not return true in JavaScript ?
- How many numbers in the given array are less/equal to the given value using the percentile formula ?
- How to remove specific elements from the left of a given array of elements using JavaScript ?
- How to convert a 2D array to a comma-separated values (CSV) string in JavaScript ?
- How to count number of occurrences of repeated names in an array of objects in JavaScript ?
- How to count number of data types in an array in JavaScript ?
- How to remove falsy values from an array in JavaScript ?
- How to move specified number of elements to the end of an array in JavaScript ?
- How to get symmetric difference between two arrays in JavaScript ?
- How to splice an array without mutating the original Array?
- How to truncate an array in JavaScript ?
- How to calculate days left until next Christmas using JavaScript ?
- How to get tomorrow’s date in a string format in JavaScript ?
- How to convert UTC date time into local date time using JavaScript ?
- How to check for two timestamp for the same day?
- How to get seconds since epoch in JavaScript?
- How to compare date part only without comparing time in JavaScript?
- How to check the input date is equal to today’s date or not using JavaScript ?
- Get the relative timestamp difference between dates in JavaScript
- How to check if one date is between two dates in JavaScript ?
- How to check if the given date is weekend ?
- How to format current date in MM/DD/YYYY HH:MM:SS format using JavaScript ?
- How to check a date is valid or not using JavaScript ?
- How to get the day and month of a year using JavaScript ?
- How to get the first day of the year in JavaScript ?
- How to generate all combinations of a string in JavaScript ?
- How to replace line breaks with br tag using JavaScript ?
- How to split multiline string into an array of lines in JavaScript ?
- How to convert image into base64 string using JavaScript ?
- How to check whether a passed string is palindrome or not in JavaScript ?
- How to get the number of occurrences of each letter in specified string in JavaScript ?
- How to find the longest word within the string in JavaScript ?
- How to find unique characters of a string in JavaScript ?
- How to create an element from a string in JavaScript ?
- How to get the first three characters of a string using JavaScript ?
- How to check a given string is an anagram of another string in JavaScript ?
- Convert a number to a string in JavaScript
- How to add method to String class in JavaScript ?
- How to create hash from string in JavaScript ?
- How to check the given element has the specified class in JavaScript ?
- How getElementByID works in JavaScript ?
- What is shadow root and how to use it ?
- What is the use of the “no-js” class in HTML ?
- How to Combine multiple elements and append the result into a div using JavaScript ?
- How to get the information from a meta tag using JavaScript ?
- How to check if an element is visible in DOM ?
- Replace a DOM element with another DOM element in place
- How to remove an HTML element using JavaScript ?
- How to check a JavaScript Object is a DOM Object ?
- Set the focus to HTML form element using JavaScript
- How to store data in the DOM ?
- How to specify the URL that will process the data supplied through input(s) when the form is submitted?
- How to store data to DOM ?
- How to get elements of specific class inside a div ?
- How to read information from nested objects in DataTables ?
- How to Convert CSV to JSON file and vice-versa in JavaScript ?
- Working with APIs in JavaScript
- Difference Between JSON and BSON
- Difference Between JSON and AJAX
- How to convert JSON results into a date using JavaScript ?
- How to swap key and value of JSON element using JavaScript ?
- How to send a JSON object to a server using Javascript?
- How to Convert JS Object to JSON String in JQuery/Javascript?
- How to convert JSON data to a html table using JavaScript/jQuery ?
- Deserializing a JSON into a JavaScript object
- How to pretty print JSON string in JavaScript ?
- Interesting facts about JSON
- Converting JSON text to JavaScript Object
- JavaScript How to add an element to a JSON object ?
- How to declare variables in different ways in JavaScript?
- How to replace the names of multiple object keys with the values provided using JavaScript ?
- How to get the first non-null/undefined argument in JavaScript ?
- Shorthand Syntax for Object Property Value in ES6
- Motivation to bring symbols in ES6
- What are decorators and how are they used in JavaScript ?
- How to use Typescript with native ES6 Promises ?
- How to clone array in ES6 ?
- Array Helper Methods in ES6
- How to create Text Editor using Javascript and HTML ?
- Generate a Random Birthday Wishes using JavaScript
- How to Design Digital Clock using JavaScript ?
- JavaScript Project on Todo List
- Create a Mobile Toggle Navigation Menu using HTML, CSS and JavaScript
- Simple Tic-Tac-Toe Game using JavaScript
- HTML | Scientific Calculator
- How to Create Image Lightbox Gallery using HTML CSS and JavaScript ?
- How to preview Image on click in Gallery View using HTML, CSS and JavaScript ?
- Last Updated : 26 Dec, 2022
Pre-requisite: Global and Local variables in JavaScript
Local Scope: Variables that are declared inside a function is called local variables and these are accessed only inside the function. Local variables are deleted when the function is completed.
Global Scope: Global variables can be accessed from inside and outside the function. They are deleted when the browser window is closed but are available to other pages loaded on the same window. There are two ways to declare a variable globally:
- Declare a variable outside the functions.
- Assign a value to a variable inside a function without declaring it using the “var” keyword.
Example: In this example, we will define global variables with user input and manipulate them from inside the function
Please Login to comment...
- nehasharmatechnians
- shobhit_sharma
- amitsingh2730
- javascript-functions
- JavaScript-Questions
- Web Technologies
Improve your Coding Skills with Practice
Start your coding journey now.

How to Define Global Variable in a JavaScript Function
A JavaScript variable is a container for storing data values. To declare a global variable, you can use the var at global scope like this:
Watch a video course JavaScript - The Complete Guide (Beginner + Advanced)

Alternatively, assign the property to a window because, in browsers, global variables declared with var are properties of the window object:
In ECMAScript 2015 specification, let, class, and const statements at global scope create globals that are not properties of the global object.
However, avoid using the global scope and wrap your code in a scoping function and use local variables to that scoping function, and make your other functions closures within it like this:
Global and Local Variables
Local function variables are declared inside a function in JavaScript. Local variables can be accessed only within the specified function. That is why, you can't reach them from any other function in the document.
It is recommended to use local variables in JavaScript functions because it allows using variables with the same name, as they are local variables that stay within separate functions. While using local variables, you can access them in the current function; in other words, the program will only access a variable in the scope of that variable.
All the variables created outside of functions are called global variables. These objects can be accessed throughout the website. They require different names for your global variables; otherwise, the browser will fail to display your desired action. Global variables have a global JavaScript scope. All functions can access it throughout the whole web page.
Related Resources
- How to Write a Function that Accepts Any Number of Arguments in JavaScript
- How to Measure Time Taken by a Function to Execute
- How to Find out the Caller Function in JavaScript
- How to Check if a Variable is of Function Type
- How to Check if Function Exists in JavaScript
- How to Check if the Variable is Undefined
- How to Unset a JavaScript Variable
JS Tutorial
Js versions, js functions, js html dom, js browser bom, js web apis, js vs jquery, js graphics, js examples, js references, javascript scope.
Scope determines the accessibility (visibility) of variables.
JavaScript has 3 types of scope:
- Block scope
- Function scope
- Global scope
Block Scope
Before ES6 (2015), JavaScript had only Global Scope and Function Scope .
ES6 introduced two important new JavaScript keywords: let and const .
These two keywords provide Block Scope in JavaScript.
Variables declared inside a { } block cannot be accessed from outside the block:
Variables declared with the var keyword can NOT have block scope.
Variables declared inside a { } block can be accessed from outside the block.
Local Scope
Variables declared within a JavaScript function, become LOCAL to the function.
Local variables have Function Scope :
They can only be accessed from within the function.
Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.
Local variables are created when a function starts, and deleted when the function is completed.
Function Scope
JavaScript has function scope: Each function creates a new scope.
Variables defined inside a function are not accessible (visible) from outside the function.
Variables declared with var , let and const are quite similar when declared inside a function.
They all have Function Scope :
Global JavaScript Variables
A variable declared outside a function, becomes GLOBAL .
A global variable has Global Scope :
All scripts and functions on a web page can access it.
Global Scope
Variables declared Globally (outside any function) have Global Scope .
Global variables can be accessed from anywhere in a JavaScript program.
Variables declared with var , let and const are quite similar when declared outside a block.
They all have Global Scope :
JavaScript Variables
In JavaScript, objects and functions are also variables.
Scope determines the accessibility of variables, objects, and functions from different parts of the code.
Advertisement
Automatically Global
If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.
This code example will declare a global variable carName , even if the value is assigned inside a function.
Strict Mode
All modern browsers support running JavaScript in "Strict Mode".
You will learn more about how to use strict mode in a later chapter of this tutorial.
In "Strict Mode", undeclared variables are not automatically global.
Global Variables in HTML
With JavaScript, the global scope is the JavaScript environment.
In HTML, the global scope is the window object.
Global variables defined with the var keyword belong to the window object:
Global variables defined with the let keyword do not belong to the window object:
Do NOT create global variables unless you intend to.
Your global variables (or functions) can overwrite window variables (or functions). Any function, including the window object, can overwrite your global variables and functions.
The Lifetime of JavaScript Variables
The lifetime of a JavaScript variable starts when it is declared.
Function (local) variables are deleted when the function is completed.
In a web browser, global variables are deleted when you close the browser window (or tab).
Function Arguments
Function arguments (parameters) work as local variables inside functions.

COLOR PICKER

Get your certification today!

Get certified by completing a course today!

Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your Suggestion:
Thank you for helping us.
Your message has been sent to W3Schools.
Top Tutorials
Top references, top examples, web certificates, get certified.
What is Global Variable JavaScript?
A global variable in javascript is a variable having global scope, meaning, it can be accessed from anywhere inside the programme.
What is Global Scope?
Scope of a variable stand for where it will be available to use inside the programme. Variable having global scope are accessible everywhere inside the programme.
What is Automatically Global?
When we initialize a variable without it's declaration first, it results in making that variable global automatically. The reason behind this behavior is, initialization without declaration is the same as initializing the variable into the window object like this window.myVal = 10 in the code below.
Note: In "Strict Mode", initializing a variable without its declaration first doesn't make the global variable automatically.
Above, we have a function myFun which is getting called, inside the myFun function myVal get initialized a value, but myVal is not declared first. As result, myVal will automatically become a global variable. Printing the myVal on console outside it's scope prints 10 as output, which verifies that myVal is a global variable now.
How does JavaScript Global Variable work?
When a global variable in javascript is declared it get moved on top of the global scope , i.e. it gets into call stack immediately in the starting, due to hoisting, where it is available to use everywhere inside the programme.
Above, we have a global variable myVal which is used in two consecutive functions addOne and print . In addOne function we added 1 into the myVal and prints the value of myVal on console in the print function.
- Using a global variable to keep track of display theme-
Above, we have a global variable themeVal having the value of display color which is "dark" . Then two if conditional blocks are calling the darkTheme and lightTheme functions based on condition. As result, will be called darkTheme and print the "current value of theme is dark" on the console as output.
- Declaring an automatic global value-
Above, we have a function add in which myVal get assigned a value of 100 without declaration of myVal first. As result, when add function get called myVal becomes a global variable, and prints "My value is 100" on console as output when display function get called.
How to declare Global Variables in JavaScript?
To declare a global variable in javascript we have to declare a var , const or let variable outside of any block or function, inside the global scope.
Above, we declare global variable myVal and assigned a value of 10 . myVal is accessible inside the myFun function also which verifies that myVal is a global variable.
What’s the Difference Between a Global var and a window.variable in JavaScript?
To declare a global variable using global var , we have to declare a var variable into the global scope. But, to declare a global variable using window.variable, we have to explicitly write window. followed by variable name and value like this window.variableName= value .
Example of global variable declared using global var -
Above, we declared a global variable using global var and assigned a value of 10 .
Example of global variable declared using window.variable -
Above, we have a function myFun in which we declared a window.variable and assigned a value of 20 . Here, both the examples will get assigned at the same place which is window object.
Variables in javascript are the building block of any program, it helps to give the named reference to any types of data used in the program, learn more about JavaScript Variables .
Conclusion:
* Global variable in javascript is a variable declared in the global scope.
- It is available to use everywhere inside the programme.
- Variable assigned a value without it's declaration first become a global variable.
- To declare a global variable in javascript we can use the global variable method or window. Variable.


JavaScript Tutorial
Javascript basics, javascript objects, javascript bom, javascript dom, javascript validation, javascript oops, javascript cookies, javascript events, exception handling, javascript misc, javascript advance, differences.
Interview Questions
- Send your Feedback to [email protected]
Help Others, Please Share

Learn Latest Tutorials

Transact-SQL

Reinforcement Learning

R Programming

React Native

Python Design Patterns

Python Pillow

Python Turtle

Preparation

Verbal Ability

Company Questions
Trending Technologies

Artificial Intelligence

Cloud Computing

Data Science

Machine Learning

B.Tech / MCA

Data Structures

Operating System

Computer Network

Compiler Design

Computer Organization

Discrete Mathematics

Ethical Hacking

Computer Graphics

Software Engineering

Web Technology

Cyber Security

C Programming

Control System

Data Mining

Data Warehouse
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on [email protected] , to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- Graphic Designing
- Digital Marketing
- On Page and Off Page SEO
- Content Development
- Corporate Training
- Classroom and Online Training
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected] Duration: 1 week to 2 week

This forum is now read-only. Please use our new forums! Go to forums

Can you change a global variable's value from within a function?
This is a conceptual question rather than one specifically about the lesson.
I understand the idea that a local variable is independent of a global variable, and that they can both exist within the same program without interfering. My question is, what if I want to use a function to change a global variable? If I change a variable’s value from within a function, will it just get reset back to the global value once the function is done running?
Answer 4f85e83354041f0003007e5e
Javascript is a little bit different than other programming languages in the sense that you can modify global variables within functions without returning them. For example:
Answer 4f85eee84c734d000300a631
Ahhhhh, ok. This makes sense. Thank you!
Popular free courses
Learn javascript.

Apr 5, 2019
Why can’t I access global variables inside my function in Javascript ?
When you declare global variable in javascript, you can access it from inside a function like so:
However, if you create a variable inside the scope of the function with the same name as a globalVariable, you lose access to the value of globalVariable inside the scope of the function.
If you read the code above by the order of which line gets executed, this is what you’d think would happen:
- create globalVariable and assign it a value.
- Call someFunction.
- log value of globalVariable to the console. You’d expect this to log I am a globalvariable
- create a new local variable with the same name as globalVariable. globalVariable and give it a value.
- Log this new local variable. You’d expect I am a local variable as the same name as globalVariable to be printed.
However, you actually get an error. J avascript will tell you that globalVariable is not defined ReferenceError:globalVariable is not defined
Explanation:
This is because regardless of where you define your variable, it will hoist the variable to the top of their enclosing scope. Which means, if a variable is defined in a scope, javascript moves it all the way at the top of the scope. This is the same reason you can call a function in javascript on line 1 even though the function doesn’t get defined until line 2.
As a result in second example, you lose access to the globalVariable defined outside the scope of the function, because it has been hoisted to the top of the scope (aka inside the function).
More from Krishna Regmi
A tech-savvy creator type — leading change through data-driven decisions, and customer-first mentality.
About Help Terms Privacy
Get the Medium app

Krishna Regmi
Text to speech
Javascript Global Variables-How to create and access them in JS self.__wrap_b=(t,n,e)=>{e=e||document.querySelector(`[data-br="${t}"]`);let s=e.parentElement,r=R=>e.style.maxWidth=R+"px";e.style.maxWidth="";let o=s.clientWidth,i=s.clientHeight,c=o/2-.25,l=o+.5,u;if(o){for(;c+1 {self.__wrap_b(0,+e.dataset.brr,e)})).observe(s)};self.__wrap_b(":R15dol6:",1)

- What are the variables in JS?
Variables in JavaScript are containers that can store values that can be accessed, updated, or used as and when required by the user. An important idea that we should understand is that variables aren’t themselves values but they are sort of like boxes where different values can be stored and modified.
We can declare variables in javascript using “var“.Both these keywords allow the declaration of a variable. Now an obvious question is why we require two keywords to perform the same function. This is where the concept of scoping comes into the picture.
- What is scope in JS?
Scope in JavaScript refers to the current context of code, which determines the accessibility of variables to JavaScript. The two types of scope are local and global :
- Global variables are those declared outside of a block(using var, window object).
- Local variables are those declared inside of a block(using let, const).
- Global Variables
Variables defined outside any function, block, or module scope have global scope . We can access variables in global scope from any point in the application. Global variables are available for the lifetime of the application.
A variable declared inside a function will be undefined when called from outside the function:
When we run the code above, JavaScript will throw the ReferenceError: username is not defined on the console.log() line . This is because the username variable scope is limited locally inside the getUsername function, so it can’t be accessed outside the function.
But when we declare the variable outside of the function, we can log the variable both inside and outside the function:
We will see both console.log can access the username variable because it’s considered a global variable:
Global variables that we declared are kept inside a global object. In the browser, our global variables are automatically assigned as a property of the window object. We can access the username variable using username or window.username as in the following example:
But this kind of behavior is only triggered when we create a variable using the var keyword. Variables created with either the let or const keyword won’t be assigned as a property of the window object.
Var statement
The var statement declares a function-scoped or globally-scoped variable, optionally initializing it to a value. var declarations, wherever they occur, are processed before any code is executed. This is called hoisting and is discussed further below.
Variable hoisting
Another unusual thing about variables in JavaScript is that we can refer to a variable declared later, without getting an exception.

This concept is known as hoisting . Variables in JavaScript are, in a sense, “hoisted” (or “lifted”) to the top of the function or statement. However, variables that are hoisted return a value of undefined . So even if we declare and initialize after we use or refer to this variable, it still returns undefined .
The above examples will be interpreted the same as:
Because of hoisting, we should try to place all var statements in a function as near to the top of the function as possible. This best practice increases the clarity of the code.
let and const are hoisted but not initialized . Referencing the variable in the block before the variable declaration results in a ReferenceError , because the variable is in a “temporal dead zone” from the start of the block until the declaration is processed.
- Creating Global Variables
We can create global variables by creating a property of the global object. In the browser context, this means that we create it as a property of the window object. In web pages, the global object is a window, so you can set and access global variables using the window.variable syntax.
There’re a few ways to do this. One way is to define it as a property of the window object. Then we can reference it as foo or window.foo anywhere in our code.
Another way is to use the var keyword in the top level of our code. That is, it’s not nested in any block. We can define it as follows,
- Accessing global variables
We can get and set global variables just like how we declared it. For example, if we declared:
Then we can reference window.foo and assign values to them. If we declare it with var at the top level as in:
Then we can either write:
Accessing a global variable is required a lot of times. If a variable is going to be used throughout the program it is important that we declare the variable in the global scope. But, because JavaScript allows the re-declaration of the same variables, it can easily become a problem if a function is using a variable with the same name as a global variable in its scope.
Normally accessing this variable’s value will return the value of the current scope variable. For example,
Here, the function’s age variable overshadows the global age variable. This is the default behavior in not only JavaScript but some other languages as well. But JavaScript has the answer to this problem.
Using the global window object, we can access the global variable. The window object is the global object that represents the browser window. All the variables declared in the global scope become the variable of the window object. To access this window object, we have to use the object dot notation .
Why global variables should not be used frequently?
Software developers “globally” consider creating global variables bad for a reason.
First, because they can access the variable from anywhere, that means any part of our code that calls the variable can change its value. This means any other developer will find it hard to reason about the role that the variable plays in our code. This also makes it hard to debug when we find errors in your program.
Global variables also make it difficult for testing code separately for obvious reasons. If the variable we need is at line 7 on a different file and our function is at line 2000 of another file, we still need to run these files together, even if they have nothing else in common.
A global variable will exist through the lifetime of our application, occupying memory resources as long as the application is running. If we have thousands of code lines and that global variable is used only in two or three lines, then our global variable will keep that memory occupied when it should be released for other tasks.
Principle of Least Privilege
There’s a software engineering called the “principle of least privilege (or exposure)”, which suggests that proper software design hides details unless and until it’s necessary to expose them. We often do exactly this in module design, by hiding private variables and functions inside closure and exposing only a smaller subset of functions/properties as the public API.
Block scoping, where variables are localized to a specific block(eg-if block…), is an extension of this same mindset. Proper software puts variables as close as possible, and as far down in scoping/blocking as possible, to where it’s going to be used.
We know this exact principle instinctively. We already know that we don’t make all variables global, even though in some cases that would be easier . Why? Because it’s bad design. It’s a design that will lead to (unintentional) collisions, which will lead to bugs .
So, we stick our variables inside the function they are used for.
Also when we nest functions inside of other functions, we nest variables inside those inner functions, as necessary and appropriate. And so on.
To conclude, global variables are good only when it’s built into the JavaScript engine. Your code will be easier to understand, debug and control when the scope of the declared variables is limited to the part of the code that actually uses it. That is all for now. Hope you learned something new today.
Free money-back guarantee
Unlimited access to all platform courses
100's of practice projects included
ChatGPT Based Instant AI Help
Structured Full-Stack Web Developer Roadmap To Get A Job
Exclusive community for events, workshops
Sharing is caring
Did you like what Krishnaditya Biswas wrote? Thank them for their work by sharing it on social media.
- What are variables in JavaScript?
- Features Of JavaScript
- What is scoping and hoisting in JavaScript? Levels of scoping in JS
- Hoisting in JavaScript
Learn coding interactively.
Popular tutorials, popular examples, reference materials, learn python interactively, js introduction.
- Getting Started
- JS Variables & Constants
- JS console.log
- JavaScript Data types
- JavaScript Operators
- JavaScript Comments
- JS Type Conversions
JS Control Flow
- JS Comparison Operators
- JavaScript if else Statement
- JavaScript for loop
- JavaScript while loop
- JavaScript break Statement
- JavaScript continue Statement
- JavaScript switch Statement
JS Functions
- JavaScript Function
- Variable Scope
JavaScript Hoisting
- JavaScript Recursion
- JavaScript Objects
- JavaScript Methods & this
- JavaScript Constructor
- JavaScript Getter and Setter
- JavaScript Prototype
- JavaScript Array
- JS Multidimensional Array
- JavaScript String
- JavaScript for...in loop
- JavaScript Number
- JavaScript Symbol
Exceptions and Modules
- JavaScript try...catch...finally
- JavaScript throw Statement
- JavaScript Modules
- JavaScript ES6
- JavaScript Arrow Function
- JavaScript Default Parameters
- JavaScript Template Literals
- JavaScript Spread Operator
- JavaScript Map
- JavaScript Set
- Destructuring Assignment
- JavaScript Classes
- JavaScript Inheritance
- JavaScript for...of
- JavaScript Proxies
JavaScript Asynchronous
- JavaScript setTimeout()
- JavaScript CallBack Function
- JavaScript Promise
- Javascript async/await
- JavaScript setInterval()
Miscellaneous
- JavaScript JSON
- JavaScript Date and Time
- JavaScript Closure
JavaScript this
- JavaScript 'use strict'
- Iterators and Iterables
- JavaScript Generators
- JavaScript Regular Expressions
- JavaScript Browser Debugging
- Uses of JavaScript
Related Topics
JavaScript let Vs var
JavaScript "use strict"
- JavaScript Closures
JavaScript Variable Scope
In this tutorial, you will learn about variable scope in JavaScript with the help of examples.
Video: JavaScript Variable Scope
Scope refers to the availability of variables and functions in certain parts of the code.
In JavaScript, a variable has two types of scope:
- Global Scope
- Local Scope
A variable declared at the top of a program or outside of a function is considered a global scope variable.
Let's see an example of a global scope variable.
In the above program, variable a is declared at the top of a program and is a global variable. It means the variable a can be used anywhere in the program.
The value of a global variable can be changed inside a function. For example,
In the above program, variable a is a global variable. The value of a is hello . Then the variable a is accessed inside a function and the value changes to 3.
Hence, the value of a changes after changing it inside the function.
Note : It is a good practice to avoid using global variables because the value of a global variable can change in different areas in the program. It can introduce unknown results in the program.
In JavaScript, a variable can also be used without declaring it. If a variable is used without declaring it, that variable automatically becomes a global variable.
For example,
In the above program, variable a is a global variable.
If the variable was declared using let a = "hello" , the program would throw an error.
Note : In JavaScript, there is "strict mode"; in which a variable cannot be used without declaring it. To learn more about strict, visit JavaScript Strict .
A variable can also have a local scope, i.e it can only be accessed within a function.
Example 1: Local Scope Variable
In the above program, variable a is a global variable and variable b is a local variable. The variable b can be accessed only inside the function greet . Hence, when we try to access variable b outside of the function, an error occurs.
- let is Block Scoped
The let keyword is block-scoped (variable can be accessed only in the immediate block).
Example 2: block-scoped Variable
In the above program, variable
- a is a global variable. It can be accessed anywhere in the program.
- b is a local variable. It can be accessed only inside the function greet .
- c is a block-scoped variable. It can be accessed only inside the if statement block.
Hence, in the above program, the first two console.log() work without any issue.
However, we are trying to access the block-scoped variable c outside of the block in the third console.log() . This will throw an error.
Note : In JavaScript, var is function scoped and let is block-scoped. If you try to use var c = 'hello'; inside the if statement in the above program, the whole program works, as c is treated as a local variable.
To learn more about let versus var , visit JavaScript let vs var .
Table of Contents
Sorry about that.
Related Tutorials
JavaScript Tutorial

IMAGES
VIDEO
COMMENTS
var Global = 'Global'; function LocalToGlobalVariable() { // This creates a local variable. var Local = '5'; // Doing this makes the variable available for one
How to change the value of a global variable inside of a function using JavaScript ? · Declare a variable outside the functions. · Assign a value
How to Define Global Variable in a JavaScript Function ; let yourGlobalVariable = "global value"; ; function display() { ; (function () {
If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable. This code example will declare a global variable
To declare a global variable in javascript we have to declare a var, const or let variable outside of any block or function, inside the global
To declare JavaScript global variables inside function, you need to use window object. For example:.
Javascript is a little bit different than other programming languages in the sense that you can modify global variables within functions without returning
However, if you create a variable inside the scope of the function with the same name as a globalVariable, you lose access to the value of globalVariable
We can declare variables in javascript using “var“.Both these keywords allow the declaration of a variable. Now an obvious question is why we
In the above program, variable a is a global variable and variable b is a local variable. The variable b can be accessed only inside the function greet . Hence