Search code examples
javascriptarraysreserved-words

Why is "closed" a reserved word is JS?


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>

Solution

  • 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