Introduction to objects  
Interactive code examples (desktop only):
Click on the green run button to run the code. Play with the code, make changes and see how this impacts the results.
Do you not see code snippets below? Please use your browser refresh button.
//Objects are an extremely useful data structure that is used in JavaScript quite extensively.
//They allow us to group properties and methods operating on these properties together, as well as the ability to inherit useful common methods.
//You can define objects in several ways, but let us introduce only a couple of these for now.
//Object literals:
//This will be an empty object...
let obj1 = {};
//This will be an object with one propery...
let obj2 = {num1: 40};
//This will be an object with two properties.
//Note the syntax. We use opening and closing curly brackets to define the obejct. We use key followed by a colon followed by a value to define a property (key-value pair). Properties are separated from one another by a comma.
let obj3 = {num1: 40,
num2: 50
};
//Let us show the three objects in the console...
console.log(obj1, obj2, obj3);
//Another way to create an object is to use the Object constructor (Object) and the new keyword. Don't worry if this doesn't make sense for now.
let obj4 = new Object();
console.log(obj4);
//We can now add properties to obj4 using the dot notation...
obj4.num1 = 50;
obj4.num2 = 60;
//Let us show our object again in the console...
console.log(obj4);
0 comments