What is the difference between a javascript attribute and a javascript variable?
When assigning values ββin javascript, I ran into this
var obj = {
resultCodeId: data[i].resultCodes[j].resultCodeId
};
var resultCodeId= data[i].resultCodes[j].resultCodeId;
How "?" and "=" are fundamentally different in javascript? Can a variable have properties as well, or just objects in javascript have properties?
source to share
=
- for an object property or assignment to a global / local variable.
:
is only intended for assigning properties when defining an object.
See also: You can delete
property. You cannot delete
change the 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
source to share
A property is usually associated with a javascript object.
var obj = {
name: 'test', --> property
getName: function(){ --> property
return this.name
}
};
Opposite variables are used inside functions and even outside them.
var global = "string"; --> variable
function test(){
var local = "string"; --> variable
}
But the basic idea of ββboth a property and a variable remains the same as for storing or pointing to an object in memory.
-
':' is used whenever you want to bind an attribute to an object.
-
'=' is used whenever you want to store actual data or reference in memory
source to share
Let's take a look at your example,
- var obj = {resultCodeId: data [i] .resultCodes [j] .resultCodeId}; this means that resultCodeId is the memeber of obj. You can access it as obj.resultCodeId .
- var resultCodeId = data [i] .resultCodes [j] .resultCodeId; It is a global variable and all global variables are properties of the window.so object you can access it like window.resultCodeId .
Additionally:
var resultCodeId = data [i] .resultCodes [j] .resultCodeId; this operator inside an object / function will be treated as a local varible and can only be accessed inside that object / function.
source to share