Do I need a semicolon after an if statement?

Why is no semicolon used at the end of the if-statement?

I believe the semicolon would only be needed at the end of each line of code within the curly brackets.

4 Likes

I found this explanation:

Your Guide to Semicolons in JavaScript

19 Likes

Why are the curly braces in different lines to the main code. I’ve seen the following syntax quite a bit now.
if (true) {
console.log(‘This message will print!’);
}

Can’t I write it like this?

if (true) {console.log(‘This message will print!’);}

1 Like

The idea of giving separate lines to the braces is to make them more visible and easy to distinguish. There is no good reason write scrunched up code when white space is free.

19 Likes

My coding background is VBA (a Microsoft application language). In that you pretty much have to break apart things like if/if else/etc. It is very helpful to increase readability, especially for longer blocks of code. Many conditional statements will execute several things, not just one, and it’s easier to keep up with what is happening and in what order if you can scan down the list, rather than across. It also allows for easier commenting.

1 Like

Is x = 5; an expression or a statement and can someone please explain what the difference between an expression and a statement is. I read multiple articles and watched multiple videos, but I don’t get what they mean by, “An expression always resolves to a value and a statement is telling the computer what to do”

is a statement.

 x + 5    =>  resolves to a value

is an expression.

x = x + 5

is a statement. All assignments are statements.

 x += 5

is also a statement.

5 Likes

Ah ok! Thank you

So an expression always resolves to a value.

Expressions:

  • 2 + 5 => resolves to the numeric value 7
  • 5 => resolves to the numeric value 5
  • "Hello " + "World!" => This resolves to the string "Hello World!" so its an expression…right?

A statement is basically an action that the computer performs

Statement

  • Variable declaration => The computer creates a new variable
  • Variable assignment => The computer assigns a value to a variable
  • if...else statement => The computer checks a condition and runs a block of code depending on the result

Is this correct? Can you please provide an example of an expression in code?

Right.

Yes.

const foo = x => x ** 2

The anonymous function on the right hand side is an expression. Functions either resolve to a return value or None.

1 Like

Is the whole arrow function an expression? I just realized that its called a function expression! What’s the difference between a function declaration and a function expression?

A declaration starts with the function keyword and is declared with a parameter list and a block (the body)

function foo (param) {
    //  code
}
1 Like

@mtf Thank you! Great explanations!

1 Like