0

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 ?

3 Answers 3

2

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)
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

i know about this. What i dont understand is why name is not undefined.
copy the html from pastebin.com/JbL89E6m and open it in your browser to see this
0

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

1 Comment

copy the html from pastebin.com/JbL89E6m and open it in your browser to see this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.