简体   繁体   中英

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..

在此输入图像描述

I tested it in Chrome and Firefox developer tools.

Note : I use clear() to clear the console

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

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

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM