(Created page with "==Object basics== As with many things in JavaScript, creating an object often begins with defining and initializing a variable. Try entering the following line below the JavaS...") Tag: 2017 source edit |
No edit summary |
||
Line 3: | Line 3: | ||
const person = {}; | const person = {}; | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Now open your browser's JavaScript console, enter | Now open your browser's JavaScript console, enter <code>person</code> into it, and press <code>Enter</code>/<code>Return</code>. You should get a result similar to one of the below lines:<syntaxhighlight lang="js"> | ||
[object Object] | [object Object] | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Line 22: | Line 22: | ||
}; | }; | ||
</syntaxhighlight> | </syntaxhighlight> | ||
After saving and refreshing, try entering some of the following into the JavaScript console on your browser devtools:<syntaxhighlight lang="js"> | |||
person.name | person.name | ||
person.name[0] | person.name[0] |
Latest revision as of 11:14, 3 December 2021
Object basics
As with many things in JavaScript, creating an object often begins with defining and initializing a variable. Try entering the following line below the JavaScript code that's already in your file, then saving and refreshing:
const person = {};
Now open your browser's JavaScript console, enter person
into it, and press Enter
/Return
. You should get a result similar to one of the below lines:
[object Object]
Congratulations, you've just created your first object. Job done! But this is an empty object, so we can't really do much with it. Let's update the JavaScript object in our file to look like this:
var person = {
name: ['Bob', 'Smith'],
age: 32,
gender: 'male',
interests: ['music', 'skiing'],
bio: function() {
alert(this.name[0] + ' ' + this.name[1] +
' is ' + this.age + ' years old. He likes ' +
this.interests[0] + ' and ' + this.interests[1] + '.');
},
greeting: function() {
alert('Hi! I\'m ' + this.name[0] + '.');
}
};
After saving and refreshing, try entering some of the following into the JavaScript console on your browser devtools:
person.name
person.name[0]
person.age
person.interests[1]
person.bio()
person.greeting()
You have now got some data and functionality inside your object, and are now able to access them with some nice simple syntax!
Source of this example: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Basics