syntax:
functions name(param1, param2){
return {
param1 : param1,
param2: param2
};
}
Note: The above syntax can be reduce if the functions parameter and the key has the same.
functions name(param1, param2){
return {
param1,
param2
};
}
Note: This reduce key and value can be inferred by the compiler that the value is the same with the key.
=================
function yourBook(author, quantity, year){
return {
author: author,
quantity: quantity,
year : year
};
}
function displayYourBook(){
let obj = yourBook("Death Note", 100, 2010);
for(x in obj){
document.writeln(obj[x]);
}
}
=================
HTML
displayYourBook()
Result:
Death Note 100 2010
Note:
1. If during document.write(obj[x]), you did not include the object name and just write the variable x like this document.write(x), the name of the keys will be displayed instead of their values.
2. for each - This works like in java for each. You set the variable in a range of collection. Just like this for(x in obj), you can read this as let x iterate through a collection of data in the object called obj.
3. in - This is a special operator use to test if for example a certain key is within that object.
if("author" in obj){
document.write("There is a key named author in object obj.");
}
4. When creating an object and you put an integer in a key name, it will be sorted. And take note of this, if you quote an integer name key like "4", it will be converted to integer and will still be sorted but if you add a plus sign inside that quoted integer like "+4", it will not be sorted.
==================
let obj = {
4: "flowers",
2: "animals",
5: "stones"
};
function displayYourObject(){
for(x in obj){
document.write(obj[x]);
}
}
==================
HTML
displayYourObject()
Result:
animals flowers stones
YOU ARE READING
Javascript Programming
RandomI am just documenting things what i learned online in here. I do express things in my own words. And I create my own program samples which serves as my practice. I do this so that when someday I would need some notes to review, I can just visit in h...
