-2

const doSomething = (foo) => {
  foo.push('rsa')
  foo = ["World"]
  return foo;
}

let blah = ["Hello"];
console.log(blah);
doSomething(blah);
console.log(blah);

Please Explain me the output

output will be like below I am really confused with javascript so please can anyone explain this.

output will be like below I am really confused with javascript so please can anyone explain this.

output will be like below I am really confused with javascript so please can anyone explain this.

[
  "Hello"
]
[
  "Hello",
  "rsa"
]
adiga
  • 34,372
  • 9
  • 61
  • 83

1 Answers1

0

The point is that arrays are passed as references (pointers if you like) In your function you made foo point to another array but the original array is still in memory

const doSomething = (foo) => {
  foo.push('rsa')
  foo = ["World"] // foo is a local variable that references an array, you changed it locally. The original array still exists.
  return foo;
}

let blah = ["Hello"];
console.log(blah); // this is obvious
doSomething(blah); // you are passing the array reference to doSomething(). that function pushes 'rsa'
console.log(blah); //you print the array with the pushed 'rsa' item
bel3atar
  • 913
  • 4
  • 6