Sometimes called an object for short. A JavaScript object literal is like a series of named variables, each with their own value, packaged into a single item – the object. Curly braces create an object literal
var student = {};
Like Python’s dictionary
JavaScript’s object literal
var person = {
name: 'Sarah',
age: 35
};
Python’s dictionary
py_dict = {
'name': 'Sarah',
'age': 35
}
Accessing Object Properties
An object Literal variable stores data as key/value AKA property/value pairs separated by commas.
var person = {
name: 'Sara',
age: 35,
treehouseStudent: true,
skills: ['JavaScript', 'HTML', 'CSS']
};
alert(person.name); // More common
alert(person['name']);
var message = "<p>Hello. My name is "+ person.name +"</p>";
person.country = 'US'; // Add new property to object
message += "<p>I live in the "+ person.country +"</p>";
person.name = 'Elizabeth'; // Edit property
message += "<p>But I wish my name were "+ person.name +"</p>";
message += "<p>I have "+ person.skills.length +" skills: ";
message += person.skills.join(', ') +"</p>";
document.write(message);
Iteration
var person = {
name: 'Sara',
age: 35,
treehouseStudent: true,
skills: ['JavaScript', 'HTML', 'CSS']
};
for ( var prop in person ) {
console.log(prop, ': ', person[prop]);
}
Example
const myString = {
string: "Programming with Treehouse is fun!",
countWords: function(){
const wordArray = this.string.split(' ');
return wordArray.length;
}
}
myString.characters = myString.string.length;
myString.string = "I love full stack JavaScript";
var numWords = myString.countWords();
Using arrow functions throws an error, as arrow functions treat this
differently. Use regular function declaration;
...
countWords: () => {
const wordArray = this.string.split(' ');
return wordArray.length;
}
...