Passing parameters by value and by reference in JS. Code exa... open

Passing parameters by value and by reference in JS. Code examples

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators

Strings, numbers, logical values are passed to the function by their value. This means that the function is not passed exactly value and its copy.

Consider an example:

    function change(x) {
        x = 2 * x;
        console.log("x in change:", x);
    }

    var n = 10;
    console.log("n before change:", n); // n before change: 10
    change(n);                          // x in change: 20
    console.log("n after change:", n);  // n after change: 10

Objects and arrays are passed to the function by reference. This means that the function receives the object or array itself, and not its copy:

    function change(user) {
        user.name = "Tom";
    }

    var bob = {
        name: "Bob"
    };
    console.log("before change:", bob.name);    // Bob
    change(bob);
    console.log("after change:", bob.name);     // Tom

However, if we try to reset the entire object or array, the original value will not change:

    function change(user) {
        //complete reinstallation of the object
        user = {
            name: "Tom"
        };
    }

    var bob = {
        name: "Bob"
    };
    console.log("before change:", bob.name);    // Bob
    change(bob);
    console.log("after change:", bob.name);     // Bob

another:

    function change(array) {
        array[0] = 8;
    }
    function changeFull(array) {
        array = [9, 8, 7];
    }

    var numbers = [1, 2, 3];

    console.log("before change:", numbers);     // [1, 2, 3]
    change(numbers);
    console.log("after change:", numbers);      // [8, 2, 3]
    changeFull(numbers);
    console.log("after changeFull:", numbers);  // [8, 2, 3]
0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation