카테고리 없음

06/29/19 Javascript Study 1 : Expression vs Statement

vision_coding 2019. 6. 29. 23:17

This blog post looks at a syntactic distinction that is unfortunately quite important in JavaScript: the difference between expressions and statements.

Statements and expressions

JavaScript distinguishes expressions and statements. An expression produces a value and can be written wherever a value is expected, for example as an argument in a function call. Each of the following lines contains an expression:

myvar

3 + x

myfunc("a", "b")

Roughly, a statement performs an action. Loops and if statements are examples of statements. A program is basically a sequence of statements (we’re ignoring declarations here). Wherever JavaScript expects a statement, you can also write an expression. Such a statement is called an expression statement. The reverse does not hold: you cannot write a statement where JavaScript expects an expression. For example, an if statement cannot become the argument of a function.

Similar kinds of statements and expressions

The difference between statements and expressions becomes clearer if we look at members of the two syntactic categories that are similar.

If statement versus conditional operator

The following is an example of an if statement:

var x; if (y >= 0) { x = y; } else { x = -y; }

Expressions have an analog, the conditional operator. The above statements are equivalent to the following statement.

var x = (y >= 0 ? y : -y);

The code between the equals sign and the semicolon is an expression. The parentheses are not necessary, but I find the conditional operator easier to read if I put it in parens.

Semicolon versus comma operator

In JavaScript, one uses the semicolon to chain statements: foo(); bar() For expressions, there is the lesser-known comma operator: foo(), bar() That operator evaluates both expressions and returns the result of the second one.

Examples: > "a", "b" 'b' > var x = ("a", "b"); > x 'b' > console.log(("a", "b")); b

 

 

Edited from. 

https://2ality.com/2012/09/expressions-vs-statements.html

 

Expressions versus statements in JavaScript

Book, exercises, quizzes (free to read online)

2ality.com