Changing, Adding and Deleting properties

We can manipulate any property of a JavaScript object.

In order to change a property, we use the assignment operator.

For example for our object:

var darkChoco = { cacao:”80%”, milk:”0%”, grams:100 };

If we write

darkChoco. milk = “10%”;

we change the property from "0%" to "10%".

What do you think will happen if we write darkChoco["milk"]= "50%" ? Try it in the console.log();

Answer:

The new value of the milk will be “50”. When using the assignment operator in an object we can change any of its properties. So, in this case, we changed "0%" to "50%".

In order to add a property in an object we just write a new name:value pair. For example, if I wanted to add the property sugar:"10%" I would write:

darkChoco.sugar = "10%"

Moreover, we can remove object properties. This is done using the delete operator.

Example:

delete darkChoco.milk;

Exercise

  1. We have uploaded the 62.js file on our WEB server. The URL is https://cnc-wp1.ellak.gr/vasilisNameWEB2/JSvasilis/62.js. Copy this URL and paste it into your browser to see what this file includes.
  2. Open your editor, create a new file and save it as exersice12.2.04.html in the folder "yourNameWEB2JS".
  3. Add a link to the js file in your HTML code
  4. Using the theory discussed here, change, add and delete parts of the file. The browser's output should be as shown in the following image:

Solution: