Search code examples
javascriptarraysobject

How Can I Change Constant Array in Javascript?


I have an array data but it declared with const. I am rather confused to change the data in array. Here is my array:

const person = {
   name: "Person A", ---> the data I want to change
   age: 100,
   favDrinks: [
     "coffee",
     "temulawak", --->> the data I want to change
     "tea"
       ],
 greeting: function() {
     console.log("Hello World"); --->> the data I want to change
   }
 }

How can I change the data of person.name, person.favDrinks[1], and greeting function of "Hello World". Is there a possible way to change constant data? I want to change to text strings. Here is my code :

function personName(nama ){
  let person.name = nama;
    person.push("name:" nama );

}

console.log(personName("Molly"));

But they are all wrong. Please help me. Thank you. :)


Solution

    • person is an object, not an array.
    • You can change properties values of a constant object.

    Working Demo :

    const person = {
        name: "Person A",
      age: 100,
      favDrinks: [
        "coffee",
        "temulawak",
        "tea"
      ],
        greeting: function() {
        console.log("Hello World");
      }
     };
     
    person.name = "Person B";
    person.favDrinks[1] = "Soft Drinks";
    person.greeting = function() {
        console.log('Hello Guys!');
    }
    
    console.log('updated object', person);