InterviewSolution
| 1. |
What Will Be The Output Of Code Below? var Salary = "1000$"; (function () { console.log("original Salary Was " + Salary); var Salary = "5000$"; Console.log("my New Salary " + Salary); } )(); |
|
Answer» The OUTPUT would be undefined, 5000$. Newbies often get tricked by JavaScript's HOISTING concept. In the code above, you might be EXPECTING salary to retain its value from the outer scope until the point that salary gets re-declared in the inner scope. However, due to hoisting, the salary value was undefined instead. To UNDERSTAND this better, have a look of the code below: var salary = "1000$"; (function () salary variable is hoisted and declared at the top in the function's scope. The console.log inside returns undefined. After the console.log, salary is redeclared and assigned 5000$. The output would be undefined, 5000$. Newbies often get tricked by JavaScript's hoisting concept. In the code above, you might be expecting salary to retain its value from the outer scope until the point that salary gets re-declared in the inner scope. However, due to hoisting, the salary value was undefined instead. To understand this better, have a look of the code below: var salary = "1000$"; (function () salary variable is hoisted and declared at the top in the function's scope. The console.log inside returns undefined. After the console.log, salary is redeclared and assigned 5000$. |
|