News for hackers. Stuff that matters.
Re:Statements vs. Expressions by simiones on Thursday July 14, 2022 @05:50AM (#32093958)
That doesn't really work, since `alert("Hello, World!")` or `doSomething()` are usually statements, not expressions; while `new SomeFunction()` is usually an expression, as is `'abc' in ['abc']`

I think that, in the context of JavaScript, if you want a "quick and dirty" way to differentiate them, the `console.log( /* put thing here */ ) ` idea from the article is the best way to go - if you can validly put the thing there, it's an expression, otherwise it's a statement.

Re:Statements vs. Expressions by mxben on Thursday July 14, 2022 @07:28AM (#32094519)
`alert("hello")` is an expression and also a statement.

  a = alert("hello"); // Assigns a to undefined
What isn't an expression? An `if` statement is not an expression.

  a = if (true) alert("hello"); // Uncaught SyntaxError: Unexpected token 'if'
Re:Statements vs. Expressions by simiones on Thursday July 14, 2022 @10:26AM (#32096468)
My point was that GP's rule of thumb (if it has a keyword, it's a statement, otherwise is an expression) is wrong on both ends.

A JS program is composed out of statements, which may contain expressions. In particular, in JS, any expression is also valid as a statement. This is not true in all languages (for example, `2` is not a valid statement in Go).

Re:Statements vs. Expressions by mxben on Thursday July 14, 2022 @11:06AM (#32096944)
> My point was that GP's rule of thumb (if it has a keyword, it's a statement, otherwise is an expression) is wrong on both ends.

I do agree!

Sorry to bother you but I am a bit confused about this part of your comment:

> `alert("Hello, World!")` or `doSomething()` are usually statements, not expressions;

Can you please clarify what you mean here? Do you mean `alert("Hello, World!")` is an expression? Or do you mean it is not an expression? Or did you mistype?

Your `console.log( /* put thing here */ )` test is a pretty good one and indeed `console.log(alert("Hello, World!"))` passes this test.

Re:Statements vs. Expressions by tsimionescu on Thursday July 14, 2022 @02:48PM (#32099987)
I meant that you would usually encounter those as statements, as in the following example:

  function foo() {
    alert("Hello, World!");
    doSomething();
  }
And not as expressions (as in your example of `console.log(alert("Hello, World"))`.

Btw, a better rule of thumb for JS is "if you can add `;` after it and not alter the meaning of the program, it's a statement; otherwise it's an expression".