0

I was trying to declare a window property when I came across this problem. What is the difference between the following two code snippets?

<script>
    window.prop=undefined;
    alert(window.prop);//undefined
    alert(prop);//undefined
</script>

And

<script>
    window.prop;
    alert(window.prop);//undefined
    alert(prop);//ReferenceError: prop is not defined
</script>

As per my understanding they are doing the same thing.

3 Answers 3

1

With window.prop=undefined;, you actually declare the variable on the window object.

window.prop; just returns the value.

Example:

a = {};
a.prop = undefined;
console.log(a); // Object {prop: undefined}
a = {};
a.prop;
console.log(a); // Object {}

In the first example, prop actually exists on a (or window, in your case), meaning it can be logged.
In the second example, it doesn't exist. When accessing normal objects, a.prop just returns undefined. However, when the object is window, it throws a reference error when accessing undefined variables on window.

Sign up to request clarification or add additional context in comments.

Comments

0

The first line of the second script block actually evaluates window.prop returning it's value (or in this case that it is undefined)

Comments

0

In the first example, window.prop is defined and the value undefined is assigned to it.

However, in the second example, the window.prop property is undefined, which means that it doesn't really exist, and then JavaScript throws a ReferenceError.

This article on MDN describes undefined value in JavaScript.

3 Comments

so undefined is a value given to a variable which states that the variable does not really exist?
@vartia, undefined is the state of a reference, if you like, that has been defined (the reference has been defined/setup) but who's value has not been assigned (maybe that makes sense/helps?)
No. undefined is a value. The point is that, if you assign it to a property of any object, this property turns to exist with the value undefined. However, if the property doesn't exist, then when you try to access this property it also returns undefined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.