First of all to all sp forum users Hello , im new tot this forum
I have a question about variable scope of JQuery. I have used the search function first but it still doenst really make sence to me how variable scope works, and when to use var in front of a variable.
can someone tell me how :
when or why to use var in front of variable?
how i can acces a variable in a function ?
You should always use var before any new variable been declared in the script as it helps to avoid getting errors throughout the script. The only time you donโt need var is when your pushing information into an array or updating that variable with a new value.
For instance, using the following example below will work fine but will consume a very tiny bit more browser memory to process it.
var hi = 'Hello';
var hi = 'Bye';
A better way to do is this is by using the example below
var hi = 'Hello';
hi = 'Bye';
NOTE: You also need to use the above example when working with arrays.
how i can acces a variable in a function ?
Its actually very simple but can also be hard depending how you setup your global and local scope variables. Below is an example of a var thats apart of the global scope
var hi = 'hello';
function saySomething() {
alert(hi);
}
saySomething();
This will work fine but for instance if you set a variable within another function you can only access it within that local scope of the function, you can get around this by either setting another var in the global scope of passing the var directly to the function you need to use it in. See the examples belowโฆ
Pass to a global scope var
var hi;
function message() {
hi = 'hello';
}
message();
function saySomething() {
alert(hi);
}
saySomething();
Pass directly to the function
function message() {
var hi = 'hello';
saySomething(hi);
}
function saySomething() {
alert(hi);
}
message();
Ah dit maakt het inderdaad duidelijker bedankt het laatste voorbeeld werkt niet
function message() {
var hi = 'hello';
saySomething(hi);
}
function saySomething(para) { // <--moet hier niet een parameter staan ?
alert(para);
}
message();