Necessity Explanation: Organization with objects in the contact list (Javascript, Codecademy)

I am having trouble understanding the two javascript functions in this Codecademy contact list project .

In particular, I got confused in conditions like "obj" or "prop". I would really appreciate it if someone could explain in detail how these functions work.

Here is the code and thanks:

var friends = {}; friends.bill = { firstName: "Bill", lastName: "Gates", number: "(206) 555-5555", address: ['One Microsoft Way','Redmond','WA','98052'] }; friends.steve = { firstName: "Steve", lastName: "Jobs", number: "(408) 555-5555", address: ['1 Infinite Loop','Cupertino','CA','95014'] }; var list = function(obj) { for(var prop in obj) { console.log(prop); } }; var search = function(name) { for(var prop in friends) { if(friends[prop].firstName === name) { console.log(friends[prop]); return friends[prop]; } } }; list(friends); search("Steve"); 
+4
source share
2 answers

obj is just the parameter name of the list function you are creating. It does not really matter. You can call it foo or object , or anything else that makes sense to you. The value of the argument that you pass to the call to the list function (above, namely friends ) is stored in the parameter in the scope of the function. That is, obj essentially becomes friends when working inside the list code.

prop is similar: it's just a variable that is created as part of the JavaScript for...in syntax. for in iterates over the property names of the object that is an argument to the in construct and stores them one at a time in prop . Again, you could call it whatever you want:

 var list = function (foo) { for (var bar in foo) { 

However, as I am sure you have learned, it makes sense to assign variable names to some values, so obj is short for an "object", since the list function works on any common object and prop not suitable for a "property".

Keep in mind that for...in iterates over property names. To access the correction value, you must use:

 if (obj.hasOwnProperty(prop)) { //access via obj[prop]; } 

The search function does this, but without the recommended hasOwnProperty check.

0
source

obj is the parameter passed in the list function. to repeat through the names of this object. For instance:

 var a = {x:5} for(var prop in a){ //here prop will be 'x' and a[prop] will be 5 (a['x'] is 5) //same goes again for objects that have multiple properties } 

In your case:

 var list = function(obj) { for(var prop in obj) { console.log(prop); // here will be logged Bill and Steve, because they are properties of friends -object } }; 
0
source

Source: https://habr.com/ru/post/1469357/


All Articles