-2

In other languages (like C++ or C#) I can make a public variable inside of a class. I want to make a global variable inside of a function.

Example:

let idk = function(){
    let num = 5;
};

// use the variable in global scope

console.log(num);
user229044
  • 232,980
  • 40
  • 330
  • 338
kanaria
  • 49
  • 7

4 Answers4

2

You can declare the variable outside without assigning to it, then assign to the variable inside without declaring it:

let num;

let idk = function () {
    num = 5;
};

// use the variable in global scope

console.log(num);
Ry-
  • 218,210
  • 55
  • 464
  • 476
1

You can expose it with window - window.num = 5 if you are in a browser.

Or in Node, use global instead.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
0

You cannot create a global variable within a function since the scope of any variable created within a function cannot be global. But you can set value to a global variable from within the function. Hope this helps.

Srinivas GV
  • 167
  • 7
0

if your program running on the browser than You can use like this

    <script>
function foo() {
    window.yourGlobalVariable = ...;
}
</script>

Or you can declire the variable oursite of the funciton and you can use it inside of the function

<script>
var globalVariable;
    function bar() {
        globalVariable = "set value into the global variable";
    }
</script>
Hoque MD Zahidul
  • 10,560
  • 2
  • 37
  • 40