1

I noticed strange issue.

Look at this jQuery:

$(function(){
    status = 1;
    status1 = 2;

    $('body').append(status+' - '+status1);
});

Fiddle

As you can see output is:

- 2

So status is system var for JavaScript or jQuery?

And is there any other vars like this?

Narek
  • 3,813
  • 4
  • 42
  • 58

2 Answers2

8

JavaScript has global variables and in browsers, global variables are properties of the global object which is window.

Now, window itself has a couple of predefined properties and some of them are read-only, like window.status [MDN] (this can also differ from browser to browser!). Creating a global variable with such a name will therefore fail (the variable already exists, but you cannot assign a new value to it).

You can find a list of predefined properties in the MDN documentation.


This one of the reasons why you should avoid global variables. If you use local variables (by declaring variables with var and if necessary, put all your code in a function), you don't have this problem:

(function() {
    var status = 'foo';
    // ....
}());
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Thanks for answer. But not all of this vars is readonly, right? I changed it to `statusbar` and it returns `1 - 2` http://jsfiddle.net/narekmarkosyan/4JrBK/5/ – Narek Apr 11 '13 at 11:08
  • An is it possible to get list of all that vars to avoid of them (in case I forgot to make them local)? – Narek Apr 11 '13 at 11:12
  • Quoting myself again: *"You can find a list of predefined properties in the [MDN documentation](https://developer.mozilla.org/en-US/docs/DOM/window)"*. – Felix Kling Apr 11 '13 at 11:15
  • 1
    Well, as I said, that differs from browser to browser. You should avoid overwriting any of them anyways. – Felix Kling Apr 11 '13 at 11:17
3

The global object window does have a property called status used for setting the text in the status bar at the bottom of the browser.

By not using the var keyword you are overwriting this property as you refer to window.status. Apparently Firefox won't let you change this though as long as the user hasn't set the dom.disable_window_status_change preference to false.

See this link for documentation and this one for a list of all "global" properties.

Also there are some words in JS that are considered reserved, so you should avoid using these, even in local scopes.

m90
  • 11,434
  • 13
  • 62
  • 112
  • Thanks, that list of Reserved Words is necessary to know too. They almost always they highlighted by IDE, that really help, instead of var from question. Right highlight will prevent this question. – Narek Apr 11 '13 at 11:15
  • Using reserved keywords out of context will throw a syntax error most of the time anyway. – Felix Kling Apr 11 '13 at 11:18