Jump to content

Declaring Variables


shane18

Recommended Posts

Try this code

var scope = "global";
function checkscope() {
  var scope = "local";
  document.write(scope);
}
checkscope();

 

 

and this

scope = "global"; 
function checkscope() {
  scope = "local"; 
  document.write(scope); 
  myscope = "local";
  document.write(myscope); 
}
checkscope(); 
document.write(scope);
document.write(myscope);

 

 

 

http://www.mredkj.com/tutorials/reference_js_intro_ex.html

Link to comment
https://forums.phpfreaks.com/topic/192006-declaring-variables/#findComment-1012007
Share on other sites

Simply put when you declare a var within a function like so

 

Var foo = 1
Function myfunc(){
var foo = 0
alert(foo);
}
myfunc();
Alert(foo);

 

You are making a local var, meaning foo is only accessible throughout the execution of your function an only to it.

The result of calling myfunc() will be an alert msg with 0

The result of the alert msg outside the func will be 1.

 

If you declare your var like so

 

var foo = 1;
Function myfunc(){
foo = 0;
alert(foo);
}
myfunc();
alert(foo);

 

The result of myfunc() will be and alert with 0.

The result of calling alert(foo) outside the function will be 0.

 

This is because when creating a var like so

foo = 0

The function take the global var.

 

An when done like so

Var foo = 1

 

The function makes a foo var in local scope.

 

Google "variable scope in javascript"

Link to comment
https://forums.phpfreaks.com/topic/192006-declaring-variables/#findComment-1012108
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.