Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: declarations vs expressions vs statements

For the past few hours I have been trying to find the difference between the 3, not just the difference, I also have been trying to find out which are sort of synonymous, MDN calls all declarations "statements", so I presume that is true. However, none of the articles and SO questions I read provided me with a cheatsheet of sorts to distinguish between the 3 (or the 2, expressions vs statements).

Something I have noticed with statements is that they all somehow involve a special JavaScript keyword like break or for or var. The articles say that an expression evaluates to something, while a statement performs an action. What is a function then ? Is it a statement-expression hybrid (since it both performs an action when called, and returns a value) ? Right now, I am assuming that this is not the case since a function call does not involve a JavaScript keyword.

And then there are declarations, is every declaration also a statement ?

I am also aware of expression statements like 20 + 5 * 2 / 3;, but aren't these virtually useless ? Why would anyone pollute their code with a line like this ?

I would be more than glad if someone could ask the above questions (or at least some of them), or if someone could provide me with some sort of a cheatsheet. Why is there so little material on a topic that appears to be so simple in such a popular language ?

like image 539
doubleOrt Avatar asked Sep 21 '17 19:09

doubleOrt


People also ask

What is the difference between a declaration statement and expression statement?

A declaration statement introduces a new variable or constant. A variable declaration can optionally assign a value to the variable. In a constant declaration, the assignment is required. Expression statements that calculate a value must store the value in a variable.

What is the difference between expression and statement in JavaScript?

Expressions produce a value, and that value will be passed into the function. Statements don't produce a value, and so they can't be used as function arguments.

Should I use function declarations or expressions?

Summary. In short, use function declarations when you want to create a function on the global scope and make it available throughout your code. Use function expressions to limit where the function is available, keep your global scope light, and maintain clean syntax.

Is a declaration a statement?

A declaration is a written statement, sworn to be the truth under penalty of perjury by any person who has direct knowledge about the issues in a court case.


3 Answers

For the past few hours I have been trying to find the difference between the 3, not just the difference, I also have been trying to find out which are sort of synonymous, MDN calls all declarations "statements", so I presume that is true.

A declaration is any construct that "declares" a variable name into existence at compile/load time before the program executes. All declared names in their respective scopes are therefore known in advance.

Statements and expressions differ from each other in that the former does not produce a value a result, whereas the latter does. So an expression may be used anywhere a value is expected, and a statement may not be used in those places.

An expression statement is one where the statement is a single expression, or several included in an expression that requires zero or more sub-expressions. While the expression(s) produce a result, the statement does not.

Here's an expression:

x = foo() + 2

A full expression statement could be explicitly shown by adding a semicolon to the end.

x = foo() + 2;

The first example can be wrapped in a set of parens, because the parens as a grouping operator expects an expression, often provided as several expressions joined by the comma operator.

The second example can not be wrapped in parens (if you include the semicolon) because then it is a statement, and does not produce a value, which the grouping operator expects to receive and return as its own value.

Something I have noticed with statements is that they all somehow involve a special JavaScript keyword like break or for or var.

While most statements do involve a keyword, not all do. Most notably, the block statement has no keyword. Instead it uses a set of curly braces to delimit its start and end.

The articles say that an expression evaluates to something, while a statement performs an action. What is a function then ? Is it a statement-expression hybrid (since it both performs an action when called, and returns a value) ? Right now, I am assuming that this is not the case since a function call does not involve a JavaScript keyword.

There are three kinds of functions in JS. If you're talking about the ones that use the function keyword, then the may be either a declaration or an expression depending on its context.

If the function is used where an expression would be expected, then it's evaluated as an expression that returns a new function object. If not, then it is expected to be a declaration, which basically creates a variable with the function object assigned to it. As a declaration, a function name is required (for the variable name). As an expression, it's optional.

I am also aware of expression statements like 20 + 5 * 2 / 3;, but aren't these virtually useless ? Why would anyone pollute their code with a line like this ?

If the resulting value is ignored, it would be useless, given that example. But here's another expression statement.

foobar();

Now we have a side effect from the function call, which is most likely desired and useful.

like image 143
llama Avatar answered Oct 07 '22 09:10

llama


Let's talk about expressions first. As you say, an expression is something that evaluates to a value. A function is a value. A function call, on the other hand, is an expression.

I don't agree with the characterization of a statement as something that "performs an action". As you say, calling a function involves running the function body, which consists of statements and declarations, so it performs actions "on the inside".

A better way to look at it is that expressions, statements, and declarations are syntactic categories. They arise from trying to describe the structure of the JavaScript grammar. See e.g. the ECMAScript 8 specification on expressions, statements, and declarations.

An expression statement like 20 + 5 * 2 / 3; is indeed useless because it has no effects, and the only point of a statement is its effects. But there are other kinds of much more useful expression statements:

  • a function call: foo();
  • assignment: x = 42; (= is an operator and can be used in expressions)
  • increment/decrement: i++; (similarly, ++ is an operator)

Statements other than expression statements tend to start with a special keyword to avoid syntactic ambiguity: The parser wants to be able to tell what kind of construct it is dealing with right from the start. Hence we get:

  • if statements: if (EXPR) STMT
  • while statements: while (EXPR) STMT
  • return statements: return; or return EXPR;
  • etc.

However, there are some statements that don't start with a keyword:

  • the empty statement: ;
  • a block: { ... }

Finally, declarations. In JavaScript the distinction between statements and declarations is somewhat arbitrary. The grammar distinguishes between the two, but in practice you can often treat them the same (e.g. the contents of a block statement are defined as a sequence of statement list items, and a statement list item is defined to be either a statement or a declaration). Declarations include:

  • function declarations: function foo() { ... } (including variants such as generators (function* foo() { ... }) and asynchronous functions (async function foo() { ... }))
  • let and const
  • class declarations

(But for some reason var foo; is classified as a statement, not a declaration.)

like image 26
melpomene Avatar answered Oct 07 '22 10:10

melpomene


There are standard definitions of these terms that all languages, including JS, follow. My takes on them are the following:

  • An expression produces a value and can be written wherever a value is expected.

  • A statement on the other hand is is a standalone unit of execution. It does not return anything.

  • A declaration is a statement in which a value is assigned to a variable.

  • All declarations are statements, but not all statements are declarations.

  • Most statements and all declarations contain expressions.

Javadoc also gives nice, succinct definitions:

An expression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value.

Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution.

Now, your theory on keywords being necessarily involved is incorrect. Here is a statement that includes a keyword:

break;

And here is one that does not:

foo();

In the first example I execute a break, whereas in the second one I call a function. Both are statements, however only one includes any special keyword.

A function is not a statement. A function call is a statement, as demonstrated above. In the case of a function that returns something, the call can also be a declaration:

var bar = foo();

And for your final question, the reason there is so little material out there on this is because this is merely an issue of semantics. People do not linger on the exact definitions of these terms.

For further clarification, I recommend taking a look at this blog post by Axel Rauschmayer that specifically talks about the difference between statements and expressions in JS.

like image 15
stelioslogothetis Avatar answered Oct 07 '22 09:10

stelioslogothetis