0

Is it possible to call a global variable that is defined in the function from outside of the function in JavaScript? For example, I can print the selected item in the console.log that is located within the function. However, if I try to fetch the same value outside of the function, it's not working. Is there anyway to fetch the value defined within a function outside the function?

var selectedItem = '';

document.getElementById('select-option').addEventListener('change', function () {
   //re-assign a new value to the variable
   selectedItem = this.value;
  // working
   consol.log('Selected Item:', selectedItem); 
});

// not working
console.log('Selected Item:', selectedItem); 

sgrimes
  • 149
  • 2
  • 11
  • What do you mean, "not working"? – Sergio Tulentsev Nov 22 '22 at 10:32
  • In the second console.log, it doesn't print the "selectedItem" and I though I couldn't fetch the value of selectedItem defined inside the function from the outside of the function. – sgrimes Nov 22 '22 at 10:40
  • 1
    console.log inside the listener function will be invoked every time the `change` event fired. but your cosole.log outside will run once and it will be empty string `''`. The value of global `selectedItem` has changed but your console will not be logged. – Zeyar Paing Nov 22 '22 at 10:41

2 Answers2

0

You can access your global state from anywhere, that part of your code is correct, you are just calling the log it too early. Check the order of operations below.

// 1. This happens first, you initialize your variable in the global scope.
var selectedItem = '';

// 2. Next you add an event listener to your HTML element (the actual event will come later)
document.getElementById('select-option').addEventListener('change', function () {
  // 4. You set a new value to the variable in the global scope
  selectedItem = this.value;
  consol.log('Selected Item:', selectedItem); 
});

// 3. You are logging the variable before the event has occurred, therefor, the variable is still empty.
console.log('Selected Item:', selectedItem);

To prove that you can access your global variable from anywhere, just wrap your code into a setInterval and trigger the event and see the value change.

// Point 3.
setInterval(() => {
  console.log('Selected Item:', selectedItem);
}, 1000);

Essentially, you need to format your code differently. If you share more information on your end-goal, we can help you better.

David Fontes
  • 1,427
  • 2
  • 11
  • 16
-1

Try to define the variable outside the function .

If you define any variable in a function definition then the variable will only be available or limited to the function only.