1

I want to create a block scoped variable in javascript using var keyword.
I don't want to create using let keyword . As it will not support all browsers.
Is there a way to achieve this through some best and generic way?

usecase: I want to use this in for loop so that for every iteration it will create a new scope.

5
  • Use shims/pollyfills, babel to transpile ES6 into ES5. Commented May 4, 2016 at 5:43
  • Yeah Pollyfills will achieve that. I could not find it in MDN. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Can we do it through core javascript? Commented May 4, 2016 at 5:45
  • In most situations you can use .forEach(). Commented May 4, 2016 at 7:25
  • @zeroflagL yeah I know that.. But I am curious to find a way to convert function scoped variable to block scoped. Commented May 4, 2016 at 7:34
  • 3
    Blocked scoped variables are only possible with let or const. Everything else is only a workaround and most of the time also more complex than forEach. Commented May 4, 2016 at 7:40

1 Answer 1

1

Create a "block" with an IIFE like so:

(function () {
  var x = "whatever";
  // x is scoped to only within this "block"
  // block code
})()

For use in a for loop to maintain scope:

for (var i = 0; i < l; i++) {
  (function (i) {
    var x = "whatever";
    // x is scoped to only within this "block"
    // block code
  })(i)
}
Sign up to request clarification or add additional context in comments.

10 Comments

You mean "IIFE". Are you suggesting replacing all blocks with functions? So if (x){var ...} becomes (function(){if (x){var ...}}())?
@RobG - That's what the transpilers usually do.
@PitaJ IIFE will do. But I want to use this in for loop. So that for every iteration it will create a new scope. I have edited the question accordingly.
Oh, and I see @RobG, you've edited your comment. In the case of an if, the block is inside, so the IIFE would be inside the if block if you want to replicate let behavior
@PJagajitPrusty - It does create a new scope. The i parameter does not refer to the same identifier as the i variable outside the IIFE. If you were to rename the i parameter of the function, you would see that is the case. Keeping the names the same is done simply for convenience.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.