If you really want it to be global, you have two options:
Declare it globally, and then leave var in the function:
var selected; function showMe(pause_btn) { selected = []; for (var i = 0; i < chboxs.length; i++) { if (chboxs[i].checked) { selected.push(chboxs[i].value); } } }
Assign window property
function showMe(pause_btn) { window.selected = []; for (var i = 0; i < chboxs.length; i++) { if (chboxs[i].checked) { selected.push(chboxs[i].value);
The window properties are global variables (you can access them with or without window. front of them). A.
But , I would not become global. Or showMe return information:
function showMe(pause_btn) { var selected = []; for (var i = 0; i < chboxs.length; i++) { if (chboxs[i].checked) { selected.push(chboxs[i].value); } } return selected; }
... and then where you need it:
var selected = showMe();
... or declare it in an area containing showMe , but not globally. Without context, it looks like # 1 above; here is a little context:
(function() { var selected; function showMe(pause_btn) { selected = []; for (var i = 0; i < chboxs.length; i++) { if (chboxs[i].checked) { selected.push(chboxs[i].value); } } return selected; }
An external anonymous function is a “scope function”, which means that selected not global, it is just common to any function.
source share