-1

html

<input type="text" id="input-el" />
    <button id="input-btn">SAVE INPUT</button>
    <script src="index.js"></script>

javascript

let myleads = [];
const inputEl = document.getElementById("input-el");

let inputBtn = document.getElementById("input-btn");
inputBtn.addEventListener("click", function () {
  myleads.push("www.awsomelead.com");
    console.log(myleads);//giving the output
  
});
console.log(myleads);//not giving the output

see here when i do "console.log(myleads);" outside the function i'm not getting the output but when i put "console.log(myleads);" inside the function i'm getting the output. my question is why "console.log(myleads);" is not working outside the function??

1 Answers1

1

The reason is that when you using console.log(myleads); outside addEventListener ,the mylead is empty,no value has been put inside it

It will execute immediately once your page is loaded,however when we execute it inside addEventListener,it will have value

let myleads = [];
const inputEl = document.getElementById("input-el");

let inputBtn = document.getElementById("input-btn");
inputBtn.addEventListener("click", function () {
  myleads.push("www.awsomelead.com");
    console.log(myleads);//giving the output
  
});
console.log(myleads);//it executed immediately,but the value is empty
flyingfox
  • 13,414
  • 3
  • 24
  • 39