3 Example(s) of Javascript Objects


Description :

Object is a list of data types that is stored as a series of name-value pairs. Each key is known as property in javascript. In this example, We are declaring person as an object with four properties firstName,lastName,age and eyeColor with value as "Michael", "Voughan", 40 and blue, Here is how we can concatenate firstName and lastname from object: person.firstName + " " + person.lastName See the code snippet:


Javascript Objects Example - 1
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
<p>Creating Object.</p>
<p id="sample"></p>
<script>
var person = {
    firstName : "Michael",
    lastName  : "Voughan",
    age       : 40,
    eyeColor  : "blue"
};
document.getElementById("sample").innerHTML =
person.firstName + " " + person.lastName;
</script>
</body>
</html>

Output

Description :

In this example, We are creating JavaScript Object with multiple property and printing their property value in paragraph tag as: "person.firstName + " is " + person.age + " years old." will print "Michael is 30 years old. See the code snippet:


Javascript Objects Example - 2
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
<p>Creating Object.</p>
<p id="sample"></p>
<script>
var person = {firstName:"Michael", lastName:"Voughan", age:30, eyeColor:"blue"};
document.getElementById("sample").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>
</body>
</html>

Output

Description :

In this example, new way to create object and assign them values and print in paragraph tag: var person = new Object(); person.firstName = "Michael"; person.lastName = "Voughan"; person.age = 50; person.eyeColor = "blue"; document.getElementById("sample").innerHTML = person.firstName + " is " + person.age + " years old.";


Javascript Objects Example - 3
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
<p>Creating Object.</p>

<p id="sample"></p>

<script>
var person = new Object();
person.firstName = "Michael";
person.lastName = "Voughan";
person.age = 50;
person.eyeColor = "blue"; 
document.getElementById("sample").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>
</body>
</html>

Output