Home > Software engineering >  Javascript - get value of variable without declaring a second one
Javascript - get value of variable without declaring a second one

Time:01-20

var i = 5;
test();

function test() {
  let i = 3;
  alert(i);
}

The above example alerts the value of the second variable that is 3. How can I code it to alert the value of the first while keeping the two with the same name? Thanks

CodePudding user response:

Use outside scope

var i = 5;
test();

function test() {
  // let i = 3;
  alert(i);
}

or make it a function parameter

// var i = 5;
test(5);

function test(i) {
  // let i = 3;
  alert(i);
}

CodePudding user response:

Use it's global namespace, i.e. the global window variable.

var i = 5;
test();

function test() {
  let i = 3;
  alert(window.i);
}

CodePudding user response:

What you probably want is this:

var i = 5;
test(i);

function test(x) {
  alert(x);
}
  • Related