0

Well, after much head scratching this afternoon; I came to realize why my array was coming back as undefined. Despite the word 'closed' not being a reserved JS word; it seems it is some kind of reserved word elsewhere and so an array cannot be called 'closed'.

My question is this; if Javascript isn't reserving this word - what is? The browser? The OS? I read that one should avoid using it as a naming convention for variables / objects but I don't understand what else is trying to use it.

Any insight would be much appreciated.

<html>
<head>
</head>
<body>
    <script>
    var greatArray = [];
    var closed = [];

    alert(greatArray.length);
    alert(closed.length);
</script>
</body>
</html>
Jordan
  • 904
  • 2
  • 12
  • 32

1 Answers1

0

It's not so much that Javascript has reserved it as that it is reserved because of where Javascript is used. Consider this:

if (myWindow.closed)

Therefore, using closed as a name for a global variable must be avoided. You can use it as a local variable, though.

As mentioned by T.J. Crowder: It's a predefined property on window that you can't redefine, and since all properties on window are globals

David Hoelzer
  • 15,862
  • 4
  • 48
  • 67
  • Ironically, your example does allow reserved words, e.g. `window.else` is valid Javascript. – georg Feb 08 '15 at 15:52
  • `window.closed` as a name for own variables **must be avoided**. – Bergi Feb 08 '15 at 15:53
  • 2
    Yet another good reason not to use globals. There's no problem at all using `closed` **not** as a global. – T.J. Crowder Feb 08 '15 at 15:53
  • That is no longer a reserved word; it is merely an object's property... – Robert Rossmann Feb 08 '15 at 15:54
  • 1
    @RobertRossmann: As of ES5, yes. Prior to that, you couldn't use reserved words as literal property names. – T.J. Crowder Feb 08 '15 at 15:55
  • 2
    `if (myWindow.closed)` is actually a really bad example, as it doesn't demonstrate using the global. Nor does the answer ever actually answer the question (the answer being: it's a predefined property on `window` that you can't redefine, and since all properties on `window` are globals...). – T.J. Crowder Feb 08 '15 at 15:58
  • T.J Crowder - Would you be able to post that as an answer so that I can mark it as being such, or will the question get closed / deleted because it is a duplicate (rendering any answer pointless)? – Jordan Feb 08 '15 at 16:03
  • As a closed question, no new answers are permitted. – vol7ron Feb 08 '15 at 22:31