vijay
vijay

Reputation: 342

Weird issue in console.log(name)

When i put console.log for any variable in browser console which are undeclared it will return Uncaught ReferenceError: variable is not defined.But when i put console.log(name) in the browser console it returns empty and undefined. See the image below. any ideas why this happens..

enter image description here

I tested it in Chrome and Firefox developer tools.

Note : I use clear() to clear the console

Upvotes: 6

Views: 3013

Answers (3)

Suren Srapyan
Suren Srapyan

Reputation: 68685

name is a global variable which is in the window object. So when you log, it goes and finds the global one, which's value is empty string ("") in your case.

console.log(name);
console.log(window.name);

Upvotes: 9

user7878837
user7878837

Reputation: 31

This is What is happening when you type the statement console.log(name):

  1. You are trying to access the variable name from within the global execution context(Logging in to the console in your case).
  2. Since you are calling it from within the global execution context it will check if the window object has a property that's called name, because in the browser the global scope is represented by the window object.
  3. since you've never declared that variable before, so typing window.name or just name should return name is not defined.
  4. but it's returning a blank line, that's because the window object has a set of pre-defined/native properties and name is one of them.
  5. window.name has by default the value "" (empty string), so it logs an empty string to your console.

Now this is what's happening when you type console.log(name100):

  1. Same as before(name100 instead of name).

  2. Same as before(name100 instead of name).

  3. You've not declared name100 neither is it a native property of the window object, so it simply returns name100 is not defined.

If you wanna check properties that is the shipped with the window object you can check this link:

Upvotes: 3

Alireza
Alireza

Reputation: 104900

Anything that doesn't have window attached to that and still working in console log or browser is a global object, in this case you are printing window.name in your console.

Try to check it this way, in your console, type the below code:

window.name = 'stackoverflow';

Then try to do console.log(name) again and you will see this time you seeing 'stackoverflow'. so basically the name you are printing in your console, is the window name...

For more info about window.name, visit the link below:

https://developer.mozilla.org/en-US/docs/Web/API/Window/name

Upvotes: 2

Related Questions