Reputation: 115
I have given two different code. One inside global window
object and second inside foo
function
Here my First code:
var undefined = 2; // 2
console.log(undefined == 2); // it gives me FALSE
var window = 5; // 5
console.log(window == 5); // it gives me FALSE
var a;
console.log(a); // it give me UNDEFINED
Here my second code:
function foo() {
var undefined = 2; // 2
console.log(undefined == 2); // true
var window = 5; // 5
console.log(window == 5); // true
var a;
console.log(a);
}
foo();
Upvotes: 2
Views: 295
Reputation: 116
In Your function foo() console.log(undefined == 2)
you mentioned //true is returning. But actually it return "false". Because "undefined" is a reserved keyword. So you can't use this as a variable. See images:
When using undefined keyword it's not working
Better use some other variable name in your foo()
When using some other variable
Upvotes: 0
Reputation: 943591
window
and undefined
are predefined (by the JS engine / browser) variables.
You can't overwrite a read only variable (if a variable already exists, then using var
in the scope it exists in does nothing).
You can declare a new variable, in a narrower scope, that masks one with the same name in a wider scope.
Upvotes: 3
Reputation: 26557
The global scope won't let you mess with just anything. That would basically cause all sorts of bad things to happen. That's why you can't change the things outside.
Inside the function, in an isolated scope, it'll let you declare variables with other names. While this is an absolutely horrible practice and you should avoid it at all costs, it won't affect anything beyond the one function.
function foo() {
var window = 5;
}
The window
in the function is not the same as the window
at the global level. The window
in the function is simply masking the outer window, making it inaccessible from inside of foo
.
Upvotes: 1