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);
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);
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);
You can expose it with window
- window.num = 5
if you are in a browser.
Or in Node, use global
instead.
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.
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>