Jquery variable scope

First of all to all sp forum users :smiley: Hello , im new tot this forum :slight_smile:

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 ?

when or why to use var in front of variable?

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();

Hope that helps.

Ah dit maakt het inderdaad duidelijker bedankt :slight_smile: het laatste voorbeeld werkt niet

function message() {
    var hi = 'hello';
    saySomething(hi);
}
 
function saySomething(para) { // <--moet hier niet een parameter staan ?
    alert(para);
}
 
message();

Ah this makes it really clear thanks to the last example does not work

Yes it should be, i have a habit of not fully proof checking my own code :blush: