0

function getx(x) {
  const id = 'x';
  console.log(id);
}


function displayx() {

  console.log(id);
}
<div class="form-check">
  <input class="form-check-input" type="radio" name="flexRadioDefault" id="flexRadioDefault1" onclick="getx(1)">
  <label class="form-check-label" for="flexRadioDefault1">
    Default radio
  </label>
</div>


<button type="button" class="btn btn-primary m-3" id="button" data-bs-toggle="modal" data-bs-target="#modal" onclick="displayx()">
        Button1
</button>

When clicked on radio button,function getx() executes properly, but after clicking on radio button, when clicked on normal button (id="button") getting error in function displax()

Error is Uncaught ReferenceError: id is not defined

I tried var also instead of const but still function displayx() is not getting value of "id". Thanks in advannce.

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
  • Either change `const id` do `var id` or move `const id` outside of the function – Dominik Matis Feb 06 '21 at 07:37
  • const id is block scoped, it is local to your function block, to solve it put the `const id = "x"`inside your global scope, outside of the function block – Aalexander Feb 06 '21 at 07:37
  • 1
    @DominikMatis Since `var` is function-scoped, changing `const id` to `var id` would have the same issue. If `const id` was moved outside, it would probably need to be made `var` or `let` since OP probably wants to re-assign it in the function call, which wouldn't be possible with `const` ;-) – Nick Parsons Feb 06 '21 at 07:43
  • 1
    @NickParsons yep u r correct – Dominik Matis Feb 06 '21 at 07:49
  • 2
    Thanks a lot @NickParsons, By declaring var id; out side the function solved my problem. – Abhishek Kamble Feb 06 '21 at 09:48

0 Answers0