I am beginer learning first steps with JS. Today i got problem with Variable. I can’t get the variable’s value outside a function.
First i have this html
<label for="inputValue">Input here</label>
<input type="text" id="inputValue">
<button id="addbtn">Button</button>
<h4 id="result"></h4>
and scripts like this:
<script>
var inputValue = "";
var outputArr = [];
//I want to get input text by clicking the button
document.getElementbyId('addbtn').addEventListener('click', function() {
inputValue = document.getElementById('inputValue').value;
outputArr.push(inputValue);
});
console.log(outputArr);
</script>
I want to get outputArr’s value which being got inside the function but the console.log print the variable’s value before changed, pls help me..
3
Answers
As you told that the problem is timing, i tried to fix them by separated the code into two listener, mousedown and mouseup, here is what i thought:
// but this can give me the answer
How do you guys think?
The issue you’re facing is related to the timing of when the console.log(outputArr) statement is executed. Currently, you have it placed outside the event listener function, so it runs immediately after the event listener is set up, but before the button is clicked and the value is assigned to outputArr.
you are getting vaue outside (in ‘outputArr’) but after click event. use your array outputArr, just that its value will be updated after button click. also use () => {} in place of function() callback
The way I would approach this is by adding an
onclick
attribute to your button like this:Then, instead of using an event listener, add a function in your JS like so:
From what I tested, it looked like your problem was at the eventListener level, not inside that. Also as Ramesh Kumar said, you need to have the console.log inside of the function or it won’t get updated when the button is pressed.