|
| 1 | +In JavaScript there are **expressions** and **statements**. We will use these words frequently to describe code. |
| 2 | + |
| 3 | +### Expression |
| 4 | + |
| 5 | +An expression returns a value. Sometimes we will say that an expression _evaluates to_ a value. |
| 6 | + |
| 7 | +The following are all examples of expressions: |
| 8 | + |
| 9 | +```js |
| 10 | +1 + 1; // returns 2 |
| 11 | +("hello"); // returns "hello" |
| 12 | +2 * 4; // returns 8 |
| 13 | +"hello" + "world"; // returns "helloworld" |
| 14 | +``` |
| 15 | + |
| 16 | +We can take the value produced by an expression and assign it to a variable. That line of code would be called a statement. |
| 17 | + |
| 18 | +### Statement |
| 19 | + |
| 20 | +A statement is some code that performs an action. Here are some examples: |
| 21 | + |
| 22 | +```js |
| 23 | +var sum = 1 + 1; // action: assigns result of `1 + 1` to variable `sum` |
| 24 | +var greeting = "hello"; // action: assigns result of the expression "hello" to variable `greeting` |
| 25 | +console.log(2 * 4); // action: logs the result of `2 * 4` to the console |
| 26 | +sayGreeting(greeting); // action: calls the function `sayGreeting` with the parameter `greeting` |
| 27 | +``` |
| 28 | + |
| 29 | +There are some other different types of statements that we will learn in the coming weeks. |
| 30 | + |
| 31 | +## Exercise |
| 32 | + |
| 33 | +You quickly find out the result of an expression by running node in a terminal window. |
| 34 | + |
| 35 | +* Open a terminal window |
| 36 | +* Run the command `node` |
| 37 | +* _You have now opened a node console (also called a REPL)_ |
| 38 | +* Type an expression and press enter |
| 39 | +* To exit the console type Ctrl+C or type the command `.exit` |
| 40 | + |
| 41 | +Example from inside a terminal window: |
| 42 | + |
| 43 | +```bash |
| 44 | +$ node |
| 45 | +> 1 + 2 |
| 46 | +3 |
| 47 | +> "hello" |
| 48 | +'hello' |
| 49 | +> var greeting = "hello" |
| 50 | +undefined |
| 51 | +> greeting |
| 52 | +'hello' |
| 53 | +> console.log(greeting) |
| 54 | +hello |
| 55 | +undefined |
| 56 | +> .exit |
| 57 | +$ |
| 58 | +``` |
| 59 | + |
| 60 | +> Notice how when we execute an expression the value it produces is printed below it. When we execute a statement, we see `undefined` printed below. This is because statements don't produce values like expressions, they _do something_. |
| 61 | +
|
| 62 | +* Write some more expressions in the node console |
| 63 | +* Assign some expressions to variables |
| 64 | +* Check the value of the variables |
| 65 | + |
| 66 | +Further reading on using the node console: https://hackernoon.com/know-node-repl-better-dbd15bca0af6 |
0 commit comments