-1

Why does the local function with the same name not conflict or over write the imported function, I would have expected the local function to overwrite and be ran instead of the one imported by the require.

//Contents of app.js

var greet = require('./greet.js');

//local greet function, how do I call this one? And why does this not redefine the identifier greet 
function greet() {
    console.log('hi');
}

greet(); //Call greet in module

//Smashing the modules import of greet
var greet = function () {
   console.log("Hello pal!");
}

greet();

and the other file is greet.js

var greet = function () {
   console.log("Hello from module!");
}

module.exports = greet;
MrDaniel
  • 583
  • 1
  • 7
  • 19
  • 3
    Your goal doesn't make sense. You can't have two things with the same name in the same context and then somehow selectively choose which one you're referring to. – Marty May 16 '17 at 23:26
  • 1
    Have a look at this question to learn more about function hoisting: http://stackoverflow.com/questions/7506844/javascript-function-scoping-and-hoisting – forrert May 16 '17 at 23:27
  • You don't have to rename anything inside `greet.js`, but you will have to rename one of the `greet`s in `app.js`. – Bergi May 17 '17 at 00:04
  • Was not the goal to have two things with the same name and selectively choose, just to understand what was happening to get the unexpected result. Main comment should have been, "this is not how JavaScript works" its not C or Java in terms of scoping. Function hoisting explanation was key to understanding the madness. – MrDaniel Apr 23 '18 at 20:28

1 Answers1

1

what you have here is a a race condition and the problem of function declaration vs function expression lets compile your code.

function greet () {...}
var greet = undefined; // reassigning greet
greet = require('...'); // reassigning greet
greet(); // ---> imported greet function execution
greet = function(){...} // ---> new implementation
greet(); // ---> new implementation execution

that in a nutshell is how your code is interpreted. not very pretty if you want to keep all the implementations just rename them... also make sure you won't execute the function expression before its being initialized because the variable will hoist but the initialization won't. I hope this makes sense and helps.

Dayan Moreno Leon
  • 5,357
  • 2
  • 22
  • 24