If you declare a var
variable outside of any function, it’s assigned to the global object, which means window
inside the browser. Since name
is a standard property of window
it already exists before your code snippet is executed. Check https://developer.mozilla.org/en-US/docs/Web/API/Window/name
So in your case calling name
equals to window.name
which is an empty string by default. To avoid such side effects it is recommended to use ES6 let/const
variable declaration.
let name;
console.log(name);
The result will be undefined
since name
in this case is not attached to a global object.