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?

+3


source to share


4 answers


=

- 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

      

+4


source


The ':' parameter is used objectally to assign a key to a value as a key / value pair. "=" is an assignment operator. It assigns a value to the variable.



Yes, a variable can have properties because an object can be assigned to a variable.

+1


source


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

+1


source


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.

0


source







All Articles