----------
RE: Question 2
------
In order to understand what's going on here, let's first establish some context about the following code:
// <---
var name=5;
console.log(typeof(name));
// --->
1. The variable `name` refers to a property on the browser's window object: `window.name`
2. Which is proven with the lines below:
// <---
var name;
name = 5;
console.log(
name === window.name &&
name === window["name"]
) // Outputs: true
// --->
This is due to the following reasons:
a.) All global variables belong to the `window` object.
b.) Variable declarations using `var` in JavaScript are automatically hoisted to the top of the current scope.
3. The `window.name` property most likely uses a setter method to assign the string value based on the `.toString()` method of the assigned value.
- See MDN:
https://developer.mozilla.org/en-US/docs/Web/API/Window/name#Notes
4. This would be similar to the following sample code:
// <---
var win = {
_name: "",
set name (value) {
this._name = value.toString();
},
get name () {return this._name;}
}
win.name = 5;
console.log(typeof(win.name));
//Outputs "string"
// --->
This mimics the same behavior as seen with `name` - a.k.a. `window.name`.
----------
RE: Question 1
------
// <---
var name;
console.log(name);
document.write(name);
// -->
The explanation for Question 2 establishes that `name` in this context is also `window.name`, which is an "empty string" value.
For this reason, `undefined` would NOT be the output for this code snippet.