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..
3 Answers
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
Rob W
No need to throw in
Node.js. Considering the question, the OP is a novice JavaScript programmer.Rob W
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.
skrat
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.
you can use this to declare an array in global scope :
let arr = [];
1 Comment
jasie
Welcome! This answer does not add any to the already given answer by gion_13 IMHO.
window.arrayname = [];, orvar arrayname = [];(in the global scope).