0

All it is, is a simple function that takes two variables and "merges" (concats) them. Code below:

function merge(var1, var2) {

    var1 += var2;
}

var a = 'a';

var b = 'b';

merge(a, b);

console.log(a);

When I call a console log inside the function, it works as planned, and prints 'ab', however on the outside of the function if I console log a, the expected result is of course 'ab' but it prints 'a'. I understand this is because a function is an asynchronous event therefore it is run after the console log outside is run however I haven't the slightest clue how to go around this. All help is appreciated.

  • This has nothing to do with asynchronicity. Be sure to read up about the scope of variables in JavaScript. [Link](https://www.w3schools.com/js/js_scope.asp) – sloppypasta Feb 06 '20 at 16:06
  • 1
    What you're changing inside `merge` isn't `a`, it's `var1`. When you do `merge(a, b)`, the **value** of `a`, not a reference to the `a` variable, is passed into `merge` and received as the value of the `var1` parameter (parameters are almost identical to variables). Then `var1 += var2; `updates `var1`, but that doesn't have any connection at all back to `a`. JavaScript is a purely pass-by-value language. See the linked [question](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language)'s answers for details. *(emphatically **not** my downvote)* – T.J. Crowder Feb 06 '20 at 16:07
  • So how would I go about fixing this issue? – StoneColdCoder Feb 06 '20 at 16:21
  • Return the result from the function to refer to it outside the function. eg. `return var1 += var2;` Note that the observed behavior stems from the design of JavaScript. When you pass string literals (eg. `'a'`) around in your program, you are _conceptually_ passing copies of the value around, not a reference to a shared copy of the value. Note that under the hood, the actual behavior might be different. Objects are, of course, handled differently. – Ben Aston Feb 06 '20 at 16:42

0 Answers0