You must know that there is multiples type of variable.
You have the global variable which is assign the the window (not a good practice). You can declare it like that :
window.varName = ...;
window['varName'] = ...;
varName = ...;
There is variable scope, that is the usual way to declare variable :
var varName = ...;
Those variables are accessible by inner scope aswell but not accessible by outer scope.
There is also object properties. You create an object and assign value :
var obj = {};
obj.varName = ...;
obj['varName'] = ...;
If you can see, there is no way you can access a scoped variable with a dynamic string, you need object or global variable. :
function changeMain(page) {
//Global variable, not recommended
window.nearbyCows = "<a>tehe</a>";
window.nearbyChickens = "<b>lol</b>";
window.search = "<i>meh</i>";
$("main").html(window[page]);
}
or :
var obj = {} //Declare outside if you want to access it outside the function
function changeMain(page) {
// var obj = {}; //or inside if you want it to be a private variable
//Object properties, recommended
obj.nearbyCows = "<a>tehe</a>";
obj.nearbyChickens = "<b>lol</b>";
obj.search = "<i>meh</i>";
/*Alternative declaration, faster to process :
obj = {
nearbyCows : "<a>tehe</a>",
nearbyChickens : "<b>lol</b>",
search : "<i>meh</i>"
}*/
$("main").html(obj[page]);
}
nearbyCowsis a local variable in this function. It's not in the scope of the caller, unless it has its own variable with the same name.window[name]to access global variables, not local variables.