Skip to content

How to access variable outside function in JavaScript | Code

To access a variable outside a function in JavaScript make your variable accessible from outside the function. First, declare it outside the function, then use it inside it.

function one(){
   var a;
   function two(){
       a = 10;
       return a;
   }
   return two();
}

You can’t access variables declared inside a function from outside a function. The variable belongs to the function’s scope only, not the global scope.

Access variable outside a function in JavaScript

Simple example code access variable outside function scope.

<!DOCTYPE html>
<html>
<body>
  <script>    
    function one(){
     var a;

     function two(){
      a = 100;
      console.log("Inner function")
      return a;
    }
    return two();
  }
   var res = one();
  console.log(res)
</script>  

</body>
</html>

Output:

How to access variable outside function in JavaScript

Another way is Not putting “var“, “let” or “const” will make the variable Public And usable outside a function.

function Play(){
  	Video = 12 // Seconds
	var Length = 15
}
console.log(Video) // Prints 12
console.log(Length) // "Lenght" is undefined

change a variable outside a function js

var global = "Global Variable"; //Define global variable outside of function

function setGlobal(){
       global = "Hello World!";
};
setGlobal();
console.log(global); //This will print out "Hello World"

Comment if you have any doubts or suggestions on this JS variable topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

1 thought on “How to access variable outside function in JavaScript | Code”

  1. .lens-input-box, .nav-search {
    position: relative;
    display: block;
    margin-top:40px;
    width: 250px;
    height: 25px;
    }

    var inputx;
    const input1 = document.querySelector(‘#search-textbox’);
    const input2 = document.querySelector(‘#lens-textbox’);

    function chooseSearchTextBox(e){
    var input = (e.target.id == ‘search-textbox’) ? input1 : input2;
    inputx = input.id;
    alert(inputx); //accessible within function scope
    }

    input1.addEventListener(‘click’, chooseSearchTextBox);
    input2.addEventListener(‘click’, chooseSearchTextBox);
    //alert(inputx); //not accessible outside the function. How do I access inputx from here? Thank you

Leave a Reply

Your email address will not be published. Required fields are marked *