Sleep Debt Calculator - Semicolon

Hi, I am working on Sleep Debt Calculator project
My code at step 9:

const calculateSleepDebt = () => {
  const actualSleepHours = getActualSleepHours();
  const idealSleepHours = getIdealSleepHours();

  if(actualSleepHours === idealSleepHours) {
    console.log("You've got enough sleep!")

  else if (actualSleepHours > idealSleepHours) {
    console.log("You sleep too much!")

  else if (actualSleepHours < idealSleepHours){
    console.log("Sleep more please!")
  else {
    console.log("Error! Something went wrong! Check your code!")

In the first if statement, I dropped “;” at the end, and this generates “Unexpected token else”. When I deleted that semicolon, the code ran. I wonder whether there’s anything wrong with the semicolon or the coding platform itself is erroneous.

I would appreciate your clarification!

We never write a semicolon before else, since it is part of an ongoing statement.

1 Like

Do you have any documents that may explain this further?

It becomes moot rather quick once we get the basics down.

Semi-colons tell the interpreter where to stop parsing a statement. Some statements are constructs with code bodies which act as delimiters. Those statements do not need an end of statement token.

if () {} else if () {} else {}
while () {}
switch () {}
function () {}

None of the above statements requires a semi-colon.

Assignments are statements with an expression on the right hand side. We end such statements with a, ;. That is one of the more obvious usages.

let a = 42;

const name = "Wee Gillis";

let y = a * x ** 2 + b * x + c;

const f = (m, b) => x => m * x + b;
console.log(f(-1, 0)(5));   // expected, -5

The last example will come up in a later unit so just take it in prose as a literal example.