Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript closures and name clobbering

Are variables defined inside an inner function that have the same name as a variable in an outer function isolated from the outer variable?

function() {
    var myTest = "hi there";
    ( function( myTest ) {
        myTest = "goodbye!";
    } )();
    console.log( myTest ); // myTest should still be "hi there" here, correct?
}

Naturally if I didn't declare myTest inside the inner function it would create a closure and modify the original. I just want to make sure that variables declared within an inner function are always isolated to that function even if their name may conflict with an outer scope.

like image 292
devios1 Avatar asked Mar 08 '12 16:03

devios1


People also ask

What is difference between closure and scope in JavaScript?

When you declare a variable in a function, you can only access it in the function. These variables are said to be scoped to the function. If you define any inner function within another function, this inner function is called a closure.

What is closure and callback in JavaScript?

Callbacks are functions that are passed into another function as an argument. Closures are functions that are nested in other functions, and it's often used to avoid scope clash with other parts of a JavaScript program.

What are the closures in JavaScript?

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.

What are promises and closures in JavaScript?

Closures refers to scope of variables where as promise are used to 'promise' that an act on something will occur when it is done on an asynchronous action.


1 Answers

Yes, they effectively do. Each function creates a new scope, and the closest scope in which a requested variable is declared always takes precedence. No exceptions.

like image 146
Ry- Avatar answered Sep 23 '22 02:09

Ry-