spread operator(... array) + push function in Array javascript

hi guys,

I am a bit confused with the two below queries, really tankful if someone can clarify my concepts. :slight_smile:

Query 1:
when using spread operator in a function it de-structure and passes it as arguments , like

let a = [1,2,3];
function x (…a) ;
it will be like function x(1,2,3) (1,2,3 passed as an argument here and not array anymore)

but one place i came across that after passing the array as spread operator we still can access indivisual items like

a[0]=1, a[1]=2…

it confuses me as i though once it is passed in the function as array it is no more array and it elelemts will be passed as simple an argument.

Query 2:
The below code works file, but at array1 =[s1,s2], i first tried to do like below,

array1=array1.push(s1)
array1=array1.push(s2)

but this return TypeError: array1.push is not a function, not sure whats the reason that we cant push the contents of s1 and s2 variables indivisually…

function sides(literals, …expressions) {

var array1=[]

var area = expressions[0];
var perimeter = expressions[1];

var s1=(perimeter+Math.sqrt(perimeterperimeter-16area))/4;

var s2=(perimeter-Math.sqrt(perimeterperimeter-16area))/4;

array1 =[s1,s2]
return array1.sort();

}

You might be confusing array spread with rest parameters. Spread spreads out arrays and other iterables to individual values whereas rest parameters pulls in multiple parameters into a single array (a lot like the arguments object). Both use ....

// spread
let nums = [1, 2, 3];
function x (one, two, three) {
    console.log(one);
    console.log(two);
    console.log(three);
}
x(...nums); // spreads out
/* logs:
1
2
3
*/
// rest
let a = 1;
let b = 2;
let c = 3;
function x (...values) { // pulls together
    console.log(values);
}
x(a, b, c);
/* logs:
[1, 2, 3]
*/
// both spread and rest
let nums = [1, 2, 3];
function x (...values) { // pulls together
    console.log(values);
}
x(...nums); // spreads out
/* logs:
[1, 2, 3]
*/
2 Likes