Understanding how mutable objects work

 Understanding how mutable objects work

In the following post you will understand how mutable objects work in JavaScript.

We will declare an array with some numbers and try to change the value and use the push method to see the results.

We will also try to reassign and see the errors that you will encounter. We will cover try and catch blocks in a separate lesson. I've used them here to demonstrate the errors.

As you can see the ARR is a constant array initialized with 1,2,3. Even though it's a constant array, changing the value is valid. Here we change the value of 2 to 25. Next we add element 5 to the end using push method.

If you try to reassign the constant, it will result in an error. Try uncommenting the line where I try to reassign to 5,6,7 to see the error.

 Let's use an array to understand this further.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title> Understanding how mutable objects work</title>
</head>
<body>
    <div id="result"></div>
    <button onclick="func1()">Run func1 function</button>
    <script>
        function func1(){
            const ARR = [1,2,3];
            try{
                ARR[1] = 25;
                ARR.push(5);
                document.getElementById("result").innerHTML = ARR;
                //ARR = [5,6,7];
            }
            catch(exception){
                document.getElementById("result").innerHTML = exception;
            }
        }
    </script>
</body>
</html>



Post a Comment

0 Comments

React