I have a problem understanding Javascript's engine technique called hoisting.
I've tried to create a var
in the top of my file to quickly access and edit, but i want to use a variable that has yet to be declared.
First attempt:
var easy_to_edit_value = "some text " + a_yet_to_be_defined_var;
//imagine loads of code so its hard to find the correct funtion to edit the log
function my_function (a_yet_to_be_defined_var){
console.log(easy_to_edit_value);
}
my_function("more text");
This generates an error at line 1 since a_yet_to_be_defined_var
is not defined.
After looking at this post: post-by-apsillers i tried again but this time declaring the var without value (so its known but undefined untill declared somewhere futheron)
var a_yet_to_be_defined_var; // now its known so this error is gone
var easy_to_edit_value = "some text " + a_yet_to_be_defined_var;
function my_function (a_yet_to_be_defined_var){
console.log(easy_to_edit_value);
}
my_function("more text");
//still undefined
//new attempt with a fresh var being set in the function before being called
var new_var;
var easy_to_edit_value = "some text " + new_var;
function my_function2 (a_yet_to_be_defined_var2){
new_var = a_yet_to_be_defined_var2;
console.log(easy_to_edit_value);
}
my_function2("more text");
//still undefined
But this outputs: some text undefined
where i was expecting the some text more text
since i filled the var before asking for it.
Please note these functions aren't ran using my_function("something")
but are triggered by this: client.on('message', my_function);
, i've seen arrow function solutions for related questions but i'm not sure how i would get that to work here.
Is it possible to make this work?