1
var a=[1,2,3];
var b = a;
a[1]=4;
alert(a);
alert(b);

I cannot figure out why is the array B is [1,4,3] as well.

My second question is: how can I complete the function sum(a)(b), so it will return the value of a+b. For example if call sum(2)(4) it will return 6?

0

4 Answers 4

6

The reason why B gets mutated as well is that when you assign var b = a, you are not copying the array. In javascript, arrays are objects and variables that hold object data are merely references to the object. The line a[1] = 4 changes the object both a and b are referencing.

For the second question, you want a curried version of sum. You can implement it simply as const sum = a => (b => a + b); Then sum(a) is the function b => a + b.

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

Comments

0

In JS var Arr1 = Arr1 does not copy it, it simply puts the reference to the array into another variable. (see @Adam Jaffe's answer)

If you are attempting to have 2 different arrays, clone the first one by slicing it at starting position.

var a=[1,2,3];
var b = a.slice(0);
a[1]=4;
console.log(a);
console.log(b);

Comments

0

var a =[1,2,3];
var b = [];
b = a.concat(b);
a[1]=4;
alert(a);
alert(b); 

function sum(a, b){
	return a + b;
}

var r = sum(2, 4);
console.log(r);

Comments

-1
function sum(a,b)
{
  return a+b;
}

var a=[1,2,3];
var b = a.slice(0);
a[1]=4;
alert(a);
alert(b);

var c=sum(2,4);

alert("c=" + c);

1 Comment

Author asked for a function that he can invoke this way: sum(a)(b) and not sum(a,b).

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.