Declaring a var
is function scoped. See What is the scope of variables in JavaScript?
You have a var last
declared at the top of your page which is global scoped.
You declare a new variable var last = 24
within the activate function. This is a different scope since it is within a function and so it will become a local variable to this activate function. The subsequent var last
declarations are ignored since one already exists in the function scope, but the values will be assigned to the local function var last
.
Your console.log(last)
is scoped to the global last
which you never give a value.
If you want to use the global last
, then remove the declaration from within your function. The compiler will then not find a local var last
in the function and will venture to the outer scope where it will find your global last
, which it will use.
var last; // global scope
jQuery('#tabs').tabs({
active: 0,
activate: function (event, ui) {
if (ui.newPanel.is("#tabs-1")) {
last = 24; // remove var declaration to use global variable
console.log(last);
}
else if (ui.newPanel.is("#tabs-2")) {
last = 48;
}
else if (ui.newPanel.is("#tabs-3")) {
last = 72;
};
}
});
console.log(last); // global scope last
var last = -1; // global scope
var whereAmI = "GLOBAL SCOPE";
$('button').on('click',function() { // new scope within function
if (new Date().getMilliseconds() % 2 === 0) {
var whereAmI = "FUNCTION SCOPE";
var last = 24;
console.log(last);
console.log(whereAmI);
} else {
last = 48;
whereAmI = "FUNCTION SCOPE";
console.log(last);
console.log(whereAmI);
}
});
console.log(last); // global scope
console.log(whereAmI); // global scope
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click Me!</button>