Reputation: 1
When I try to JS examples I've tried these functions from the w3schools and I've changed the code to recognize if JS can overwrite functions :
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1) ) + min;
}
let firstFunction = getRndInteger(1,10);
let secondFunction = getRndInteger(2,5);
console.log(`First function is working: ${firstFunction}`);
console.log(`Second function is working: ${secondFunction}`);
I've read some of the questions in stack overflow but most of the people say "JS don't overwrite functions or JS don't allow run with the same function name but this code work properly and print the results. Can anyone explain this for JS?
I've tried different functions to see the results for the functions with the same name, but it worked for every of them and exit with 0 status code.
Upvotes: 0
Views: 68
Reputation: 370769
When there are duplicate function declarations for the same name, the final function declaration takes precedence. It's as if the original one never existed - somewhat similar to if you did
var x = 4;
x = 5;
at the top of a block; the 4 gets lost, and nothing can see that x
ever had a value of 4.
While you technically could overwrite previously defined functions in a block like what you're suggesting, and it doesn't produce a syntax error, it wouldn't make any sense to do - it'd be easier to delete (or comment out) the first function from the source code.
Upvotes: 1