Reputation: 356
so we know that variables declared with the var keyword are hoisted and if we try to access their value before they have been initialized we get undefined. However, In the code below logging the name variable logs the function and not undefined why ?
console.log(name);
console.log(lol);
var name = function(args = "Hello World"){
console.log(args)
}
var lol = function(args = "Hello world") {
console.log(args)
}
the output is
function(args = "Hello World"){
console.log(args)
}
and
main.js:57 undefined
why isnt name variable undefined ?
Upvotes: 0
Views: 79
Reputation: 3440
The window which is the root scope already has a name property. Try the following and look at the output in your console. If you click the link the page that opens has MyWin as the output for name.
HTML (test.html)
<head>
<title>test</title>
</head>
<body>
<a href="test.html" target="MyWin">Click me!</a>
<script src="test.js"></script>
</body>
</html>
Javascript (test.js)
console.log("name", name);
console.log("notname", notname);
console.log("lol", lol);
var notname = function (args = "Hello World") {
console.log(args)
}
var lol = function (args = "Hello world") {
console.log(args)
}
Upvotes: 2
Reputation: 708
I think you should logging like that why you confused.
console.log(name);
console.log(lol);
var name = function(args = "Hello World"){
console.log(args)
}
var lol = function(args = "Hello world") {
console.log(args)
}
console.log(name);
console.log(lol);
Upvotes: 0
Reputation: 55250
Consider the code
console.log(test);
var test = function(args = "Hello World"){
console.log(args)
}
This will return undefined
because only declarations are hoisted. That is, your code after hoisting will be
var test;
console.log(test);
test = function(args = "Hello World"){
console.log(args)
}
Upvotes: 0