2

As question, What is the difference when a integer, string and array pass as function parameter in javascript?

Below are my question:

<html>
    <head>
        <script>
            var a = 0;
            var b = new Array();
            b.push(0);

            function Add(num) {
                num++;
            }

            function Add1(num) {
                num[0]++;
            }

            Add(a);
            Add1(b);

            alert(a);
            alert(b[0]);
        </script>
    </head>

    <body></body>
</html>

And it ended up provide two different value, why? The first result 0 and the second one is 1

1 Answer 1

3

Arrays as objects are passed in functions by reference while primitives (e.g. strings and numbers) are passed by value. Here is an example:

function test(arr, obj, prim) {
    arr[0]++;    // by reference
    obj.prop++;  // by reference
    prim++;      // by value

    return prim; // to get the amended primitive value back
}

var arr = [0],
    obj = { prop: 0 },
    prim = 0,
    result;

result = test(arr, obj, prim);

console.log(arr, obj, prim);  // [1], Object {prop: 1}, 0
console.log(result);          // 1

GOOD ARTICLE: http://snook.ca/archives/javascript/javascript_pass

Sign up to request clarification or add additional context in comments.

2 Comments

so the function will change the reference value? any extra information or reference so I can read on? Thanks
@dramasea Strings and numbers are primitive types, arrays and objects are not. You may read a nice article about it in the updated answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.