JAVASCRIPT GLOBAL VARIABLE

Lavanya



JavaScript Global Variable 

A JavaScript global variable, declared either outside a function or using the `window` object, can be accessed from any function.

Here’s a simple example of a global variable in JavaScript.

<Script>

var globalVariable = "Hello, World!";

function printGlobal() {
  console.log(globalVariable); 
}

function changeGlobal() {
  globalVariable = "Goodbye, World!";
}

printGlobal(); 
changeGlobal();
printGlobal();
console.log(globalVariable);

</Script>

"Defining a global variable in JavaScript within a function."

To declare JavaScript global variables inside a function, and accessed from any other function. 

Example

<Script>

var globalVariable;

function setGlobal() {
  globalVariable = "I'm global";
}

function getGlobal() {
  console.log(globalVariable); 
}
setGlobal();
getGlobal();

</Script>

Internals of global variable in JavaScript

When you declare a variable outside a function, it is internally added to the `window` object. You can also access it through the `window` object. 

Example

<Script>

var globalVar = "I'm global";

function scopeDemonstration() {
  var globalVar = "I'm local";

  console.log("Local:", globalVar);
  console.log("Global:", window.globalVar)
}

scopeDemonstration();

console.log("Global:", globalVar); 

</Script>


Tags
Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send