Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

value of variable has changed or not

Tags:

javascript

how to find whether a value of variable is changed or not in javascript .

like image 699
Niraj Choubey Avatar asked Jun 16 '10 06:06

Niraj Choubey


People also ask

Can the values of variables be changed?

In most cases, you can edit a variable's value. If you right-click on a variable and the Change Value command isn't faded, you can edit the displayed value.

How do you know if a variable has a value or not?

Answer: Use the typeof operator If you want to check whether a variable has been initialized or defined (i.e. test whether a variable has been declared and assigned a value) you can use the typeof operator.

What happens when variable values change?

When you reassign a variable to another value, it simply changes the reference to that new value and becomes bound to it.

Can variables change over time?

It is called a variable because the value may vary between data units in a population, and may change in value over time.


4 Answers

Ehm?

var testVariable = 10;
var oldVar = testVariable;

...
if (oldVar != testVariable)
alert("testVariable has changed!");

And no, there is no magical "var.hasChanged()" nor "var.modifyDate()" in Javascript unless you code it yourself.

like image 193
bezmax Avatar answered Oct 19 '22 08:10

bezmax


There is a way to watch variables for changes: Object::watch - some code below

/*
For global scope
*/

// won't work if you use the 'var' keyword
x = 10;

window.watch( "x", function( id, oldVal, newVal ){
    alert( id+' changed from '+oldVal+' to '+newVal );

    // you must return the new value or else the assignment will not work
    // you can change the value of newVal if you like
    return newVal;
});

x = 20; //alerts: x changed from 10 to 20


/*
For a local scope (better as always)
*/
var myObj = {}

//you can watch properties that don't exist yet
myObj.watch( 'p', function( id, oldVal, newVal ) {
    alert( 'the property myObj::'+id+' changed from '+oldVal+' to '+newVal );
});


myObj.p = 'hello'; //alerts: the property myObj::p changed from undefined to hello
myObj.p = 'world'; //alerts: the property myObj::p changed from hello to world

// stop watching
myObj.unwatch('p');
like image 37
meouw Avatar answered Oct 19 '22 07:10

meouw


Using getters and setters:

var _variable;
get variable() {
    return _variable;
}
set variable(value) {
    _variable = value;
    // variable changed
}

or if you don't need the value of the variable later:

set variable(value) {
    // variable changed
}
like image 26
Solomon Ucko Avatar answered Oct 19 '22 08:10

Solomon Ucko


If you are a firefox user you can check using firebug. If you are using IE we can put alert statements and check the values of the variables.

like image 45
Puru Avatar answered Oct 19 '22 08:10

Puru