The global scope contains a lot of variables such as status
which can cause difficulties like this, since some of them are locked to a certain type and others can't be changed. To avoid this problem, you can write your code inside of a function to get a clean scope. Variables declared with the var
keyword are function scoped, so a function does the job.
When a variable is scoped to your function rather than to the global namespace, it will not override the global variable of the same name. This means you can still access the global one via window.status
if you wish.
example (continue reading after this example for a better way):
//define your function with your code inside
function myCode(){
var status=[1,2,3];
console.log(status);
}
myCode(); //call your function
You can use a IIFE (Immediately Invoked Function Expression) to declare the function and then immediately run it without having to bind it to a global name which is very useful in this scenario.
(function(){
var status=[1,2,3];
console.log(status);
})();
Same thing, except that the function is invoked immediately. This is preferable since the goal here is to avoid having global name collisions.