codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

JavaScript Objects

Adolf Schmuck
codeburst
Published in
8 min readSep 21, 2020

--

Photo by Goran Ivos on Unsplash

Terminology

Object Written Using Literal Notation

Literal Notation

var person1 = {
name: 'Jim',
DOB: 1997,
age: function() {
return 2020 - this.DOB;
}
}

Accessing the Object

var person1 = {
name: 'Jim',
DOB: 1997,
age: function() {
return 2020 - this.DOB;
}
}
console.log(person1);
{name: "Jim", DOB: 1997, age: function}
var person1 = {
name: 'Jim',
DOB: 1997,
age: function() {
return 2020 - this.DOB;
}
}
console.log("Hello, I'm " + person1.name + " and I'm " + person1.age() + " years old.");
Hello, I'm Jim and I'm 23 years old.
console.log(person1['name']);
console.log(person1['age']());
console.log(person1['name'] + ' is ' + person1['age']() + ' years old.');
Jim
23
Jim is 23 years old.

Function Constructors

var contact = {
name: 'John Doe',
email: 'jdoe@test.com',
DOB: 1985,
age: function () {
return 2020 - this.DOB;
}
}
function Contact(name, email, DOB, siblings) {
this.name = name;
this.email = email;
this.DOB = DOB;
this.siblings = siblings;
this.age = function (DOB) {
return 2020 - this.DOB;
}
}
var john = new Contact("John Doe", "jdoe@test.com", 1985, ["Tom", "Anne"]);
var carol = new Contact("Carol Lee", "carol@jmail.com", 1965, ["David", "Mary", "Rose"]);

Accessing the Instances

var john = new Contact("John Doe", "jdoe@test.com", 1985, ["Tom", "Anne"]);
var carol = new Contact("Carol Lee", "carol@jmail.com", 1965, ["David", "Mary", "Rose"]);
console.log(john);
console.log(carol);
Contact {
name: 'John Doe',
email: 'jdoe@test.com',
DOB: 1985,
siblings: [ 'Tom', 'Anne' ],
age: [Function]
}
Contact {
name: 'Carol Lee',
email: 'carol@jmail.com',
DOB: 1965,
siblings: [ 'David', 'Mary', 'Rose' ],
age: [Function]
}
console.log("Name: " + john.name + "\n" + "Email: " + john.email + "\n" + "Siblings: " + john.siblings + "\n" + "Age: " + john.age());console.log('\n*******************************\n');console.log("Name: " + carol.name + "\n" + "Email: " + carol.email + "\n" + "Siblings: " + carol.siblings + "\n" + "Age: " + carol.age());
Name: John Doe
Email: jdoe@test.com
Siblings: Tom,Anne
Age: 35
*******************************Name: Carol Lee
Email: carol@jmail.com
Siblings: David,Mary,Rose
Age: 55

Summary

Literal Notation / Function Constructor

References

--

--

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

No responses yet