2

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();

5
  • 1
    The second code block returns, false,true,undefined Commented Jun 27, 2017 at 11:08
  • I know its not a good practice but i just wann know what actually happening under the hood of javascript while its execution Commented Jun 27, 2017 at 11:08
  • note: undefined is often passed as an argument to plugin constructors to ensure that the value is preserved and not redefined. it is really not a thing to do Commented Jun 27, 2017 at 11:10
  • @AliSomay he forgot the var before undefined, when it is here, undefined gets actually overriden and the results are what he writes Commented Jun 27, 2017 at 11:12
  • Google variable shadowing. Commented Jun 27, 2017 at 11:21

3 Answers 3

3

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.

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

Comments

1

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.

1 Comment

thnx buddy...i know it is bad practice. i just wann know .Why it is so.
0

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

Comments

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.