0

The following piece of javascript code:

function init(name) {
  function displayName() {
    var name = name || "default string";
    console.log(name); 
  }
  displayName();
}
init("parameter string"); //here is unexpected ouput: "default string"

Why does the above code not output "parameter string" as expected? Thanks in advance.

update: However, the following code works as expected:

function init(name) {
  var name = name||"Mozilla";
  console.log("init name:",name)
}
init("param string")//output: "init name: param string" as expected

what's the different between the two codes?

somggx
  • 43
  • 6
  • it should be `name = name ?? "default string";` – Dean Van Greunen Aug 28 '22 at 09:22
  • 3
    Because you explicitly told it **not** to, by declaring a *new* `name` variable in the inner scope, shadowing the outer `name` parameter. Remove the `var` so you're using the `name` parameter. – T.J. Crowder Aug 28 '22 at 09:23
  • 1
    I voted to close as typo/non-repro, but it's probably a duplicate of [this](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript), or any question asking what `var` does. – T.J. Crowder Aug 28 '22 at 09:25

2 Answers2

0

Because On the left side, you declare a variable called name which will be undefined before get initialization, so the name value on the right side will be undefined, so name variable will initialize with "default string".

function init(name) {
  function displayName() {
    var name = name || "default string";
    console.log(name); 
  }
  displayName();
}
init("parameter string"); //here is unexpected ouput: "default string"

But if you remove var as @T.J. Crowder suggest, you will re-assign the name parameter which already has value.

function init(name) {
  function displayName() {
    name = name || "default string";
    console.log(name); 
  }
  displayName();
}
init("parameter string"); //here is unexpected ouput: "default string"

If you replace var with let it will give an error "Cannot access 'name' before initialization", which explain the point.

function init(name) {
  function displayName() {
    let name = name || "default string";
    console.log(name); 
  }
  displayName();
}
init("parameter string"); //here is unexpected ouput: "default string"
Mina
  • 14,386
  • 3
  • 13
  • 26
0

Because you declared same name variable inside closure function..

The below code should work

function init(name) {
  function displayName() {
    var name1 = name || "default string";
    console.log(name1); 
  }
  displayName();
}
init("parameter string")

Otherwise you can directly check without declaring variable again

name = name || "default string";
Ramkumar G
  • 415
  • 1
  • 8