Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 345
vijay Avatar asked Apr 17 '17 12:04

vijay


2 Answers

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);
like image 51
Suren Srapyan Avatar answered Sep 24 '22 06:09

Suren Srapyan


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:

  • W3schools reference for the window object

  • MDN reference for the window object

like image 26
user7878837 Avatar answered Sep 23 '22 06:09

user7878837