R Cabardo
R Cabardo

Reputation: 21

Update Variable after Function Return

I'm new to JavaScript so I apologize if this is simple. I'm passing a couple values to my controller but after, I need to reset the global variables without refreshing the page. My code looks like this:

var userName = null;
var _delegated = false;

function setAddtionalData(value) {
  if(value == true) {
    userName = "something";
    _delegated = value;
  }
}

function getAdditionalData() {
  return {
    username: userName,
    delegated: _delegated
  };
  userName = null;        // Does not get hit
  _delegated = false;     // Does not get hit
}

But variables never get updated. Is there a way to set these without page a refresh?

Upvotes: 0

Views: 1289

Answers (2)

Malk
Malk

Reputation: 11983

Code after the return will not be executed. You need to grab the values, clear the variables, and return the grabbed values:

function getAdditionalData() {
  var retval = {
    username: userName,
    delegated: _delegated
  };
  userName = null; 
  _delegated = false;
  return retval;
}

Upvotes: 1

Adjit
Adjit

Reputation: 10305

Those values are never reached since your return statement exits out of the function.

You should save, username and _delegated to temporary variables, set them to null, and then return the object.

return statements are used to exit out of a function, so anything you put after your return statement will not happen.

Upvotes: 0

Related Questions