[SOLVED] There is Uncaught SyntaxError: Unexpected identifier when defining a variable in code block

Issue

This Content is from Stack Overflow. Question asked by Bennpoes

I have Uncaught SyntaxError: Unexpected identifier when I define a const variable in a code block. I have already checked if I missed a extra comma, colon, parenthesis, quote or bracket. But still get the error after I replaced the comma into curly brackets. It works when I remove the variables and replace the a in Math.pow in 10. So what is going wrong with the const variables?

const multipleCircles = [{
  calc1: {
    const a = 10;
    area: Math.PI * Math.pow(a, 2);
  },
  calc2: {
    const a = 100;
    area: Math.PI * Math.pow(a, 2);
  }
}];
console.log(multipleCircles);


Solution

It is not clear what you are trying but the closest with the least change to your code is this

const multipleCircles = [{
  calc1: () => {
    const a = 10;
    return Math.PI * Math.pow(a, 2);
  },
  calc2: () => {
    const a = 100;
    return Math.PI * Math.pow(a, 2);
  }
}];
console.log(multipleCircles[0].calc1());
console.log(multipleCircles[0].calc2());

This Question was asked in StackOverflow by Bennpoes and Answered by mplungjan It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?

Exit mobile version