0

I am using JS from quite a time now but still get stuck in some places with very basic concepts. Recently going through some basic questions I got stuck with this one

var employeeId = 'abc123';

function foo() {
    employeeId = '123bcd';
    return;

    function employeeId() {}
}
foo();
console.log(employeeId);

O/P : abc123

Can someone explain how the output is abc123. It might be a very basic question but any help will be appreciated.

The IT gal
  • 197
  • 1
  • 5
  • 15
  • this problem is all about scoping. Read more about this [here](https://dmitripavlutin.com/javascript-scope/) – Shubham Verma Nov 18 '20 at 08:13
  • @Shubham Scoping alone is an insufficient explanation here. It's also about the peculiarity of function declaration hoisting which produces the unintuitive outcome here. – deceze Nov 18 '20 at 08:15
  • 1
    `employeeId` gets hoisted inside of `foo`. When you write `employeeId = "123bcd"` it searches in the current scope (foo) if there is an variable named `employeeId` and yes there is the hoisted function `employeeId`. now you override the function to an string and return nothing. – bill.gates Nov 18 '20 at 08:21
  • @Ifaruki can you elaborate more. Why it is taking value from global scope? – The IT gal Nov 18 '20 at 08:23
  • You did notice [the duplicate](https://stackoverflow.com/a/49873322/476) which explains it…? – deceze Nov 18 '20 at 08:25
  • @deceze I did but the duplicate question doesn't answer my question – The IT gal Nov 18 '20 at 08:26
  • 2
    How exactly doesn't it? `function employeeId` creates a local name `employeeId`, the same as `var employeeId` would. That *shadows* the global variable by the same name, so assigning to `employeeId` inside the function does *not* change the outer variable. Is that clear enough? – deceze Nov 18 '20 at 08:28
  • 1
    mutating outside variables from inside an function is ugly and not pure. i recommend to read about [pure functions](https://www.freecodecamp.org/news/what-is-a-pure-function-in-javascript-acb887375dfe/) .pure functions helps you to write cleaner code without side effects. its a core principle about functional programming. – bill.gates Nov 18 '20 at 08:31

0 Answers0