As the title says I am struggling with how to find out if a value is greater or smaller than previous value javascript.
Lets say I am sending a variable to a method with increments or decrements.
Ex1:
value(3);
Ex2:
value(2);
Ex3:
value(4);
And the method...
function value(id){
}
So when I get the values from the "sender" i want to determine if the value is greater or smaller than the other value in my method. First value is 3. The second value is 2 -- That would lead to that the first value is greater than the new input value 2 and so on...
Any ideas?
Thanks!
As the title says I am struggling with how to find out if a value is greater or smaller than previous value javascript.
Lets say I am sending a variable to a method with increments or decrements.
Ex1:
value(3);
Ex2:
value(2);
Ex3:
value(4);
And the method...
function value(id){
}
So when I get the values from the "sender" i want to determine if the value is greater or smaller than the other value in my method. First value is 3. The second value is 2 -- That would lead to that the first value is greater than the new input value 2 and so on...
Any ideas?
Thanks!
Share Improve this question edited Jun 19, 2011 at 20:01 Pointy 414k62 gold badges595 silver badges629 bronze badges asked Jun 19, 2011 at 19:57 TobiasTobias 4943 gold badges14 silver badges31 bronze badges2 Answers
Reset to default 7You could use a closure around your function:
var value = (function() {
var previousValue = null;
return function(id) {
if (previousValue !== null && previousValue > id)
alert("You sent me something smaller than last time!");
previousValue = id;
};
})();
This has the advantage that only the "value()" function can "see" the saved "previousValue" - other code can't change the value. It's essentially like a private attribute of an anonymous object created implicitly by the function call made in that declaration.
Declare a variable outside of the function, and update that with the latest value every time the function is called.
Then simply pare the parameter with the current value in that variable to determine whether it's larger or smaller:
var current = 0;
function value(id) {
//pare id with current
current = id;
}