Is there a purpose to hoisting variables?

“Hoisting” is necessary for mutually recursive functions (and everything else that uses variable references in a circular manner): function even(n) { return n == 0 || !odd(n-1); } function odd(n) { return !even(n-1); } Without “hoisting”, the odd function would not be in scope for the even function. Languages that don’t support it require forward … Read more

Why is my JavaScript hoisted local variable returning undefined but the hoisted global variable is returning blank? [duplicate]

What is happening here is that you are accessing window.name. This is a predefined property on window, so your hoisted var name isn’t actually creating a new variable. There’s already one in the global scope with that name and by default, it has a blank string value. To observe the behavior you were expecting, you … Read more

What happens when JavaScript variable name and function name is the same?

Functions are a type of object which are a type of value. Values can be stored in variables (and properties, and passed as arguments to functions, etc). A function declaration: Creates a named function Creates a variable in the current scope with the same name as the function (unless such a variable already exists) Assigns … Read more

How JS hoisting works within functions?

JavaScript hoisting within functions means that the declaration of variables are moved to the top of the function block. When you enter foo(), var boo is redeclared instantly even though you have not reached it (because the JS engine knows that this declaration exists within the function). Accordingly, the reason that it is undefined is … Read more

Why do catch clauses have their own lexical environment?

Yes, catch clauses indeed have their own Lexical Environments. Check out what happens when it is evaluated: It creates a new one (deriving from the current one) and binds the exception-identifier to it. When executing the catch block, the current Execution Context’s LexicalEnvironment is switched to the new one, while the VariableEnvironment(“whose environment record holds … Read more

Why a variable defined global is undefined? [duplicate]

You have just stumbled on a js “feature” called hoisting var myname = “global”; // global variable function func() { alert(myname); // “undefined” var myname = “local”; alert(myname); // “local” } func(); In this code when you define func the compiler looks at the function body. It sees that you are declaring a variable called … Read more