0

I want to transfer variable using function(), but I am not sure if I am able to put variable inside of variable

I tried to put variable inside variable like this var toStore = myVariable

var myText = "Hi";

changeMyText(myText);


function changeMyText(variableToUse) {
    variableToUse = "Hello World";
    console.log(myText);
}

It does not change the content of variable myText

vaku
  • 697
  • 8
  • 17
Daw588
  • 56
  • 6

1 Answers1

2

Actually the argument you pass to function is pass by value this means that even when you change the argument value it doesn't reflect to actual value...

Here, from w3Schools - JavaScript Function Parameters

Arguments are Passed by Value

The parameters, in a function call, are the function's arguments.

JavaScript arguments are passed by value: The function only gets to know the values, not the argument's locations.

If a function changes an argument's value, it does not change the parameter's original value.

Changes to arguments are not visible (reflected) outside the function.


Objects are Passed by Reference

In JavaScript, object references are values.

Because of this, objects will behave like they are passed by reference:

If a function changes an object property, it changes the original value.

Changes to object properties are visible (reflected) outside the function


This from mdn - function deceleration | Thanks @Ivar

Primitive parameters (such as a number) are passed to functions by value; the value is >passed to the function, but if the function changes the value of the parameter, this change is not reflected globally or in the calling function.

If you pass an object (i.e. a non-primitive value, such as Array or a user-defined object) as >a parameter and the function changes the object's properties, that change is visible outside the function

Community
  • 1
  • 1
vaku
  • 697
  • 8
  • 17
  • 2
    Please note that W3Schools [isn't always the best resource](https://meta.stackoverflow.com/questions/280478/why-not-w3schools-com). We usually prefer to link to [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions). – Ivar May 26 '19 at 15:31
  • 1
    Thanks @lvar, I will remember this in future... – vaku May 26 '19 at 15:34