What is the difference between javascript property and javascript variable?
=
is for object property or global/local variable assignment.
:
is only for property assignment at object definition.
Also:
You can delete
a property.
You cannot delete
a variable.
var obj = {
p1: 'im p1',
p2: 2
};
obj.p1 = 'im updated p1'; // assign a new value to object property
var v = 'just a var'; // is global outside a function and local inside a function
delete obj.p1; // is ok
delete v; // is not ok
The ':' is used in an object way to assign a key to a value as a key/value pair. The '=' is an assignment operator. It assigns a variable to a value.
Yes a variable can have properties because a variable can be assigned an object.
A property is usually associated with a javascript object.
var obj = {
name: 'test', --> property
getName: function(){ --> property
return this.name
}
};
In contrary variables are used inside functions and even outside of them.
var global = "string"; --> variable
function test(){
var local = "string"; --> variable
}
But the underlying idea of both the property and a variable remains the same, which is to either store or point to an object in memory.
':' is used whenever you want to associate a attribute to an object.
'=' is used whenever you want to store the actual data or a reference in memory