Animations

API

Arrays

Async

Basics

Challenges

Classes

Console

Dates

Debugging

DOM Elements

DOM Methods

DOM Navigation

DOM Properties

Event Listeners

Flow Control

Forms

Functions

Global Functions

JSON

Keywords

Libraries (3rd party)

Math

Modules

Objects

Snippets

String

Types

Widgets

Window Object

JavaScript - Adding / Deleting Properties

Adding properties to an object
You can add new properties to an existing object by simply giving it a value. Assume that the person object already exists - you can then give it new properties:

person.nationality = "English";

function person(first, last, age, eye)
{
    this.firstName = first;
    this.lastName = last;
}

let father = new person("John", "Doe");
father.Age = 50;

let msg = "Father name is " + father.firstName + " " + father.lastName + ". Age is " + father.Age + "
"; document.getElementById("demo1").innerHTML = msg;;

Deleting properties to an object
The delete keyword deletes a property from an object.


let mother = new person("Jane", "Doe");
mother.Age = 50;

delete mother.Age; // or delete person["age"];

let msg2 = "Mother name is " + mother.firstName + " " + mother.lastName + ". Age is " + mother.Age + "<br />";
document.getElementById("demo2").innerHTML = msg2;

 


Adding a Method to an object
Adding a new method to an existing object is also easy.


let brother = new person("Jack", "Doe");
brother.FullName = function () { return this.FirstName + " " + this.LastName; };

let msg3 = "Brother name is " + brother.firstName + " " + brother.lastName + ". Full Name is " + brother.FullName() + "<br />";
document.getElementById("demo3").innerHTML = msg3;