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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.