How to Define an Object |
Example |
Objects are declared the same as variables
var myObj = Then we add curly braces {} in order to hold key pairs var myObj = { } // var myObj The key pairs look like this "key" : "pair" var instructor = { firstName: "William", lastName: "Iverson", class: "JScript", } Now, I want to add a function and see where it would take us. Ideally, you always want to think of a block code that is reusable. That is exactly why Object Oriented Javascript is phenomenal. In my early days of programming I was right away introduced to see the code as a block vs little parts. Debugging a block is a lot easier to isolate than dealing with waterfall style of code. Now, I want to build a function inside of the object that spews greeting: function() { alert("Hello from " + instructor.class + " class taught by " + instructor.firstName + " " + instructor.lastName) } Notice that I am calling a variable from the root of var instructor and bringing it into the greeting key. If you use greeting: function() { alert("Hello from " + class + " class taught by " + firstName + " " + lastName) } Your code will not work! By now, your code should look like this var instructor = { firstName: "William", lastName: "Iverson", class: "JScript", greeting: function() { alert("Hello from " + instructor.class + " class taught by " + instructor.firstName + " " + instructor.lastName) } Just add another curly brace } to close the object instructor and add instructor.greeting(); I gotta mention this crucial element. When you are done listing key and pairs even though they are separated by comma, do not add another comma after your very last key/pair. It doesn't work, your code will not execute. You will end up having a syntax error. :) |
|
Replacing a value inside of a keyLet's say you have assigned one value but inside of the object you need to replace it with another... This is how you do it.
|
Nesting multiple objects within oneYou can nest multiple objects inside of a main object. Below is the example. I personally love writing the code more detailed and specific. This way I have less and less errors.
|
WHEN DO I USE Array & when do i need an object? |
You use ARRAY when you need to list a list of items by numbers.
You use OBJECTS when you need to list items by names. |