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?

Jason Aller
3,66028 gold badges43 silver badges40 bronze badges
asked Oct 23, 2017 at 20:04
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.

answered Oct 23, 2017 at 20:09
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);

answered Oct 23, 2017 at 20:12

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);

answered Oct 23, 2017 at 20:14

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);
answered Oct 23, 2017 at 20:14

1 Comment

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.