Incorrect JavaScript snippet#21150
Conversation
There's an issue with one of the suggested snippets on this page.
The first suggested snippet, under the below bullet point, is incorrect:
1. Global variables of your script are, in fact, properties of `window`:
```js
const global = { data: 0 };
alert(global === window.global); // displays "true"
```
Variables declared with `const` and `let` don't become properties of the `window` object.
The only way to create a global variable that's a property of the `window` object, is to either declare a variable with `var` or initialize the variable without declaring it, like so:
Example 1: declaring variable with `var`
```js
var global = { data: 0 };
alert(global === window.global); // displays "true"
```
Example 2: initializing a variable without declaration
```js
global = { data: 0 };
alert(global === window.global); // displays "true"
```
|
Preview URLs Flaws (1)URL:
|
Elchi3
left a comment
There was a problem hiding this comment.
Great catch, thank you!
The text also says: "The point of having the window property refer to the object itself, was likely to make it easy to refer to the global object. Otherwise, you'd have to do a manual let window = this; assignment at the top of your script."
I believe that should be var window = this; there as well?
Josh-Cena
left a comment
There was a problem hiding this comment.
Yes, it was over-refactoring. Thank you and congratulations on your first contribution here—welcome aboard!
No, that's not strictly necessary. Unless you absolutely want to make your custom |
Elchi3
left a comment
There was a problem hiding this comment.
That makes sense. Thanks for the explanation, @Josh-Cena 👍
There's an issue with one of the suggested snippets on this page.
The first suggested snippet, under the bullet point below, is incorrect:
window:The above snippet displays an alert message with
falseand nottrueas suggested by the snippet, which is incorrect.Variables declared with
constandletdon't become properties of thewindowobject.The only way to create a global variable that becomes a property of the
windowobject, is to either declare a variable withvaror initialize the variable without declaring it, like so:Example 1: declaring variable with
varExample 2: initializing a variable without declaration