To set and return a variable value without creating an additional variable

Is it possible to compact the function below so there is no variable created?

    var flag=true;
    //...
    my.flagValue=function(){
        var f=flag;
        flag=false;
        return(f);
    };

Basically, to set and return (the previous) value at the same time.

Answers


Well, normally there's no way to return something before setting it. But in this specific case, you can use some magic to pull it off. Though your original code is far more readable and maintainable:

my.flagValue = function () {
    return (flag && !(flag = false));
};

If flag is true, then it will perform like this:

return (true && !(flag = false)); //!(flag = false) is true, so true is returned.

If flag is false, then it will perform like this:

return (false && !(flag = false)); //obviously returns false.

Though, I really do encourage you not to do this. It's obscure and requires a bit of logic parsing to sort out. I just wanted to demonstrate that it's possible to do what you're looking to do in this specific case.


Need Your Help

Questions about using Accelerate.framework

iphone objective-c cocoa osx

I had a few questions about Accelerate framework.

Split variables in brackets with javascript

javascript jquery html

I have already tried google but I was not able to find an answer to my problem.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.