newbie
newbie

Reputation: 14950

global variable in javascript

Good day!

I am writing a script as follows:

var prev = 0;

$(document).ready(function(){
    dynamicListOne(length, prev);
});

function dynamicListOne(length, prev){
   length++;
   prev = length;
}

But prev is always 0. How can i assign prev=length?

Thank you in advance

Upvotes: 0

Views: 183

Answers (3)

Pastor Bones
Pastor Bones

Reputation: 7351

There is no need to pass in prev as a parameter

var prev = 0;

$(document).ready(function(){
    dynamicListOne(length);
    console.log(prev)
});

function(length){
   length++;
   prev = length;
}

Upvotes: 0

gahooa
gahooa

Reputation: 137262

The prev variable in your function signature hides the global prev variable. Choose a different name and it will work :)

Upvotes: 0

Matti Virkkunen
Matti Virkkunen

Reputation: 65116

Your function takes prev as an argument so inside the function the name points to a local variable instead of the global one. Just don't add it as an argument to your function.

And think carefully if you really really want a global variable.

Upvotes: 1

Related Questions