skip to Main Content

A code block like this yields a value in chrome console and repl

{
  let x = 1;
  for (let i = 1; i < 10; i += 1) {
    x *= i;
  }
  x;
}

picture of the code in the console

Is it possible to assign the result of a block to a variable?

This will throw an error because {} is interpreted as an object here

const a = {
  let x = 1;
  for (let i = 1; i < 10; i += 1) {
    x *= i;
  }
  x;
}

3

Answers


  1. Chosen as BEST ANSWER

    It seems like eval works (I know that eval is evil)

    const a = eval(`{
      let x = 1;
      for (let i = 1; i < 10; i += 1) {
        x *= i;
      }
      x;
    }`)
    
    console.log(a)


  2. JavaScript does not have block expressions as some other languages do. As you noted, it becomes an object/error.

    What you could do is use an IIFE and return a value from it.

    const a = (() => {
      let x = 1;
      for (let i = 1; i < 10; i += 1) {
        x *= i;
      }
      return x;
    })();
    
    console.log(a)

    The point of blocks has greatly increased now that const and let have much more robust scoping rules over var. It also would be useful with the new using support as well.

    Login or Signup to reply.
  3. You have to write a function, or similar.

    const fn = () => {
      let x = 1;
      for (let i = 1; i < 10; i += 1) {
        x *= i;
      }
      return x;
    }
    
    const a = fn();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search