How to use a variable inside a function in JavaScript

Variables declared outside the function have global scope by default. It means we can use them in our functions.

Example:

<script>
    var myHello = 'hello';

    function logHello() {
        console.log(myHello);
    }

    logHello();
</script>

Output (console):

hello

How to use a variable from another function?

If you want to access a variable from another function, you can make a global variable to assign your variable to it, or use a window.

Example:

<script>
    function myVariable() {
        window.myHello = 'hello';
    }

    function logHello() {
        console.log(window.myHello);
    }

    myVariable();
    logHello();
</script>

Output (console):

hello