HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / JavaScript / JavaScript: Correct way to define global variables

JavaScript: Correct way to define global variables

We know that what global variables or constants are, these are fields which are accessible application wide. In java, it is done usually done using defining “public static” fields. Here by adding final keyword, we can change the global variable to global constant. So easy, right?

But what about javascript? These scripting languages don’t have these access modifiers etc., so what are our options?

javascript jquery

I faced a similar situation in my regular work hours and came to know that defining global variable in traditional javascript way can break in production code. Traditional way is:


var iAmGlobal = "some val"; //Global variable declaration

//Any place in other part of code

function doSomething()
{
    //iAmGlobal = "changed value";
    alert(iAmGlobal); //I am accessible here too !!
}

These type are declaration are in practice from long time and for some less fortunate mates, it result in famous “Object doesn’t support this property or method” error in java script. If you remember there is an IE bug with “var a = foo” only declaring a global for file scope. This is an issue with IE’s notorious broken interpreter.

So, what’s correct way to declare global variable in javascript then?

Correct way to declare global variable in JavaScript

The proper way is to use window object. And use the syntax like this:


var window.iAmGlobal = "some val"; //Global variable declaration with window.

//Any place in other part of code

function doSomething()
{
    alert(window.iAmGlobal); //I am accessible here too !!
    //OR
    alert(iAmGlobal); //I am accessible here too !!
}

By defining globals this way, you will make JavaScript more robust and reliable.

Important points:

  1. Define global variables with window keyword in form of “window.VAR_NAME”
  2. You can access the variable with “window.VAR_NAME” or directly “VAR_NAME”
  3. Do not use other variables with same name otherwise it may cause unwanted results

That’s all folks on this topic.

Further reading: http://stackoverflow.com/questions/4862193/javascript-global-variables

Happy learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Ilker Balpinar

    January 18, 2020

    You shouldn’t use the ‘var’ keyword for this example because of the ‘window’ is already defined as the ‘Window’ object.

  2. Balbhadra Singh Thakur

    June 10, 2016

    var window.iAmGlobal = “some val”;

    So what is need of var here i think correct way is

    window.iAmGlobal = “some val”;

  3. ravikant verma

    November 25, 2014

    hi Guys ,

    I have doubt regarding global variables. Is it available on next web page.
    Thanks

    • Lokesh Gupta

      November 25, 2014

      No. Once new page is loaded in browser, it (it’s state) is gone.

  4. komal

    December 2, 2013

    I need help to generate auto generated code for buyer like when i select India from struts2 template its code come IND01, IND02… If in case i select China code comes like CHN01, CHN02 n so on.. I am developing s/w in struts2 and hibernate 3 but i think I think we need to use javascript for this but i dont know how to use it.. Please help me out for this

    • Lokesh Gupta

      December 2, 2013

      Not sure what you are asking here. Please make it more clear. Not sure if you are looking for any ajax based solution.

      • komal

        December 3, 2013

        I want to generate automated buyer code. In struts2 template I have country name. country code buyer code. these fields i have in my buyer class(Hibernate 3) all are string variable. When i select country name from country drop down i get country code(ex. India i have IND code, Chine I have CHN code) that code is display in Buyer Code text field as prefix concatenate with increment number For Ex. If i select Indian then i want buyer code as IND001, IND002….. so on. If in case i selct 3rd buyer from China then i want to display buyer code as CHN001. then CHN002….
        Please help me for this . I am getting IND CHN prefix by using java script function but what about next number

        • Lokesh Gupta

          December 3, 2013

          Use pad function on autogenerated/ incremental numbers : https://stackoverflow.com/questions/10073699/pad-a-number-with-leading-zeros-in-javascript

  5. TheSharpieOne

    August 30, 2013

    The second example has an error.

    var window.iAmGlobal = “some val”;

    window is already declared, no need for var.

  6. Michael Wales (@walesmd)

    August 25, 2013

    My point is: if in your first example you were to alert the window.iAmGlobal variable it would work perfectly fine. There’s no need to further confuse the issue by incorrectly telling people this is how you globally scope a variable, which they shouldn’t even be doing in the first place.

    Your 300 word post would be better served teaching hoisting, rather than ” Holy shit! var duh === var duh”.

    • Lokesh Gupta

      August 25, 2013

      I do not write only for experts, rather my readers are beginners and medium level experts with some hand-on. I really need to put some words to make them clear. Anyways, I got your point.

  7. Dom Sammut

    August 24, 2013

    Indeed this issue does occur when you have your code split between multiple files in IE and you require them to communicate between each other. I think this IE issue isn’t preset in more recent versions so its not something that is a must have. If you’re in an enterprise environment with required support for old versions of IE this information can be useful.

    • Lokesh Gupta

      August 24, 2013

      True

  8. Michael Wales (@walesmd)

    August 24, 2013

    No. None of that is correct. Your first example is the equivalent of your second when run in a browser because of variable hoisting. When you use the keyword var, JavaScript will assign that variable within the current scope. In your first example that scope is the top most, which in a browser is window.

    There are tons and tons of examples of this available online, is one of the key facts thou must understand about JavaScript. If you don’t grok hoisting, your applications functioning properly is just pure dumb luck.

    • Lokesh Gupta

      August 24, 2013

      Thanks for your input. I understand this but the thing is behavior of browsers (specially IE) are always surprising. I myself have faced problem what I mentioned in “IE bug with “var a = foo” only declaring a global for file scope”.

      So, I am concluding my learning here as always go with “windows.VAR_NAME”. Yes they are identical in a fair world, but we don’t live in that.

      • Hans

        June 24, 2015

        thanks god… no “windows” needed

Comments are closed on this article!

Search Tutorials

JavaScript / jQuery Tutorials

  • Ajax Tutorial
  • jQuery – Ajax
  • jQuery – Deep Cloning
  • jQuery – Selectors
  • jQuery – All Selector
  • jQuery – Cut, Copy or Paste Events
  • jQuery – ENTER Key Press Event
  • jQuery – Keypress vs. Keydown
  • jQuery – Funny Discussion on SO
  • JavaScript – Equality vs Identity
  • JavaScript – Variable Scope Rules
  • JavaScript – Global Variables
  • JavaScript – MVC and PubSub
  • JavaScript – DOM vs. jQuery Objects
  • JavaScript – Unit Test with Jasmine
  • JavaScript – Information Masking

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces