Allen Dun
Allen Dun

Reputation: 11

JavaScript basic array and function problems

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?

Upvotes: 1

Views: 57

Answers (4)

Ashim Paul
Ashim Paul

Reputation: 100

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

Upvotes: -1

fatih
fatih

Reputation: 353

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

Upvotes: 0

Unamata Sanatarai
Unamata Sanatarai

Reputation: 6637

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

Upvotes: 0

Adam Jaffe
Adam Jaffe

Reputation: 91

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.

Upvotes: 6

Related Questions