You mention in your comments that myVariable
is a number. Since myVariable
houses a primitive type, simply use the code below:
myVariableAtSomePoint = myVariable;
Take a look at JAVASCRIPT: PASSING BY VALUE OR BY REFERENCE. Here's a quote:
When passing in a primitive type variable like a string or a number,
the value is passed in by value.
I would also suggest reading: How do I correctly clone a JavaScript object?
EDIT:
I believe that you're assuming that the placement of the function in the code affects the value of the variables. It does not. See examples below:
This:
function test () {
var myVariableAtSomePoint= myVariable;
console.log(myVariableAtSomePoint);
}
myVariable = 2;
test(); // Prints 2, instead of 1.
Is the same as this:
var myVariable = 1;
function test () {
var myVariableAtSomePoint= myVariable;
console.log(myVariableAtSomePoint);
}
myVariable = 2;
test(); // Prints 2, instead of 1.
Your problem is that you're changing the value of myVariable
before you're assigning it to myVariableAtSomePoint
. For this to work as you want, you'll need to call the test()
function before you change the value of myVariable
var myVariable = 1;
function test () {
var myVariableAtSomePoint= myVariable;
console.log(myVariableAtSomePoint);
}
test(); // Prints 1
myVariable = 2;
test(); // Prints 2
IMPORTANT: No matter the placement of the function, the code inside test()
is not executed until you call the function.