Can I define a local scope while defining a variable/const in JavaScript or TypeScript?

42 Views Asked by At

I use mostly F# and recently I've started exploring the World of JavaScript.

In F# (and many other languages) it is possible to create local scopes while defining a binding, e.g.

// F# code
let myValue =
  let internalValue = 1
  internalValue + 5

In this example myValue is assigned a value of 6, while internalValue remains invisible outside of the inner scope.

I wonder if I can do something like this in JavaScript or TypeScript. For now the closest thing I've found so far is to define a lambda and call it immediately like this:

// JS Code
const myValue = (() => {
  const internalValue = 1;
  return internalValue + 5; 
})();

This works, but doesn't look pretty. Is there anything better?

I believe this feature has it's own name, but I don't know what it is therefore I couldn't find the answer on SO.

EDIT - question clarified after a piece of feedback

This works as expected, but I wonder if the same thing can be achieved without creating the lambda?

0

There are 0 best solutions below