1

Could some one help me in explaining the below snippets. These were asked during my interview. Please post answers with reasoning.

enter image description here

Klaycon
  • 10,599
  • 18
  • 35
karthik stj
  • 57
  • 2
  • 5
  • I found this tool extremely helpful in certain cases: http://www.pythontutor.com/javascript.html#mode=edit It visualizes the execution order and shows the at the moment results to the right – LasagnaCode Sep 22 '20 at 14:29

1 Answers1

2

The first example is pretty straightforward. The employeeId is defined outside foo function, the foo function is being called, a new value is being assigned to employeeId, returns from the foo function and it prints the value.

The tricky part in the second example is the function employeeId(){} within the function foo(). When the code executes and you are in the function foo, the function employeeId will be defined/hoisted. You can think it like you are creating a variable employeeId and that you assigned a function there. Because of that, when the code actually executes, it will use this function employeeId that got defined/hoisted and it will override it with the value '123bcd'. In this way, the employeeId of the outer scope remains untouched.

Edit 1: While I was searching for providing extra resources, here is a question about hoisting and about the same problem that you've posted: JavaScript 'hoisting'

Stavros Zavrakas
  • 3,045
  • 1
  • 17
  • 30