2

In my html code, I need a global array which I use throughout my application. How to create and initialize global array variable in javascript..

5
  • 2
    window.arrayname = [];, or var arrayname = []; (in the global scope). Commented Jun 29, 2012 at 13:31
  • I want to declare that global array in function, i tried it without using var keyword, but it doesn't read that variable.. Commented Jun 29, 2012 at 13:38
  • Are you sure the array is initialized before you try to read from it? Commented Jun 29, 2012 at 13:40
  • yeah, i initialized it before reading using names = new Array(); Commented Jun 29, 2012 at 13:44
  • What code do you currently have? Commented Jun 29, 2012 at 13:52

3 Answers 3

10

You can do it several ways :
In the global scope :

var arr = [];

Binding the array to the global namespace:

window.arr = [];

or, for running the code in other environments, where the global object is not necessarily called window:

(function(global){
    global.arr = [];
})(this);
Sign up to request clarification or add additional context in comments.

Comments

0

In the browser, you can attach objects to the global scope using the window object:

window.myArray = ["foo", "bar"];

In Node.js, you can access the global scope using the global object.

3 Comments

No need to throw in Node.js. Considering the question, the OP is a novice JavaScript programmer.
Don't encourage it. Implicit variable declaration makes code less readable -> more likely to fail. In strict mode, implicit variable declaration is forbidden, and a ReferenceError is thrown.
Implicit variable declaration is what? There's no such thing, you probably mean global variable. There's no reason why would that increase chances of fail, it's all authors responsibility. It's not the best practice around, but in many cases it works pretty well, like when you want to provide some JSON data on the HTML page for scripts, to avoid extra XHR.
0

you can use this to declare an array in global scope :


let arr = [];


1 Comment

Welcome! This answer does not add any to the already given answer by gion_13 IMHO.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.