When you call a function, like so:
const myVar = test("hi");
you have passed the return value of your function (the function named test
, called with the parameter “hi”), and stored it into a variable named myVar
. But that doesn’t mean you’ve stored the function itself, merely its return value.
Each time you call the function, it executes again. With whatever you pass as your parameter. In the case of
console.log(test('hi') );
we are calling the function, and then we log whatever value it returns. When that value has been returned, our function no longer exists in memory. We haven’t stored a reference to this particular run of the function, we have simply run the function, got a value, and the browser’s memory management tools will “garbage collect” our now-used function for us.
There are ways of doing what you’re suggesting - creating a function that stores a value, and can simply be called with no value later - but they’re a bit more complex. What happens in that case is, when we call the function for the first time, it creates a space in memory (often called a “scope”), kind of a function context, and then it returns an function (rather than returning a static value). Here’s an example of that:
// this outer function takes in a variable, creates a function scope,
// and then passes back the inner function. By passing the function back, we have a way
// to access the parameters we've "stored" in our function scope.
var saySomething = function(whatToSay){
// this function has access to the parameters we've passed, even after the function itself has
// run. So long as we have something that refers into this memory space, the browser's
// garbage collection will leave it alone.
return function(whoToSayItTo){
// this function also takes a parameter, but it can still access the outer function's as well!
return whatToSay+" "+whoToSayItTo;
}
}
// Here's how it might be used:
let sayHelloTo = saySomething("Hello");
let sayHelloInItalianTo = saySomething("Buon Giorno");
let sayHelloInBrazilianTo = saySomething("Bom dia");
// Each of the above functions created a unique space. Each is stored.
console.log(sayHelloTo("world!")
console.log(sayHelloInItalianTo("terre!")
const myVar = sayHelloInBrazilianTo("Bob");
console.log(myVar);
A little deep, but that’s a bit of an answer to the question of “why are my parameters not being kept?!?”