As an example am I allowed to use the same variable and parameter? What issues can I run into?
Sample code
function mytask(name,title){
var name = name;
var title = title;
var showalert = ("Hi " + name + " your job title is " + title);
console.log(showalert);
return showalert;
}
document.write(mytask("dan", "administrator"));
Well in javascript you can think that, scopes are defined my curly brackets:
{And}, and inside a scope variables can be redefined, so look at:But this is just half true, actually what happens is that the interpreter goes over the code, and moves all
varstatements to the beginning, while they’re assigned anundefined(and all arguments are defined and taken from stack), and then the code you wrote will run. So anyvarafter the first is simply ignored. And the code you wrote is equal to:So your re-deceleration, and assignment is redundant. Anyway – the scope is not changing, nothing else will differ.
Edit
The interpreter goes over your code, with executing anything, any
var x = y;statement will split intovar x = undefined;andx=y;. And thevar x = undefined;will be moved to the top of the code. And thex=y;will be at the same place as the original statement. If you didn’t understand the stuff about the stack, don’t bother, that’s how compilers convert function calls to assembly – it’s worth knowing in case you have time; but not THE important thing here.Anyway – just after those changes, and maybe some optimizations are made, the resulting code is executed. This is not the code you wrote, but an equal one. What you pointed out in redefining the arguments is an edge case where this transformations become visible.