javascript make global variable code example
Example 1: javascript define global variable
window.myGlobalVariable = "I am totally a global Var";
var myOtherGlobalVariable="I too am global as long as I'm outside a function";
Example 2: create global variable inside function JavaScript
<script>
function foo() {
window.yourGlobalVariable = ...;
}
</script>
Example 3: global scope js
const color = 'blue'
const returnSkyColor = () => {
return color;
};
console.log(returnSkyColor());
Example 4: global variable in js
If you trying to acess a variable from a function
then,
let i=0;
function as(){
i=1
}
as()
console.log(i)
const d=()=>{
console.log("from d: ",i)
}
d()
the output
1
from d : 1
better way is window.myGlobalVariable = "your variable"
not encourged to use global variable at all