JS Const Variable with Array & Objects


CONST ARRAYS

The code above has an array variable called numbers holding three values. Even though the numbers array is a const you’re able to update or change the variable. For example, you can add another number to the numbers array by using the push method. Methods are actions you perform on the array or object.

const numbers = [1,2,3];
numbers.push(4);
console.log(numbers) // Outpusts [1,2,3,4];


CONST OBJECTS

The modifying principle applies to an object for example.

const user = {
  name: "Gary",
}

user.age = 29
console.log(user) // {name: "Gary", age: 29
 

The code above creates a user object with a name property then it assigns a new age property to object. One thing to remember const does not stop array and objects from being modified it only stops the variable itself from being reassigned or being overwritten for example.

const user = {
  name: "Gary",
}

person = { name: "Bob" } // Uncaught TypeError: Assignment to constant variable.
 

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript</title>
  <script>
    const a = {
      name : "Ram",
      age : 25
    };

    a.name = "Yahoo Baba";
    a.age = 55;
    console.log(a);
  </script>
</head>
<body>
</body>
</html>