JavaScript (1) Statement, Expression, I/O and Operators

You can test JS program with your web browser(e.g. firefox, chome). Open the web browser and press "F12" and select "Console". Now you can test your program with that console in your browser. To type multiple lines into the console at once, use "shift" + "enter" to move to the next new line.

1. Statements:

In a computer language, the statement is composed of a group of words, numbers, and operators which performs a specific operation.

a = b + 2;

The characters "a" and "b" are called variables. The variable is similar to a container which can be used to store the result of the operation.

On the other hand, the number "2" is just a value itself which is called a literal value, because it stands alone without being stored in a variable.

Most statements in JavaScript conclude with a semicolon (;) at the end.


2. Expressions:

1. Statements are made up of one or more expressions.

2. An expression is any reference to a variable or value, or a set of variable(s) and value(s) combined with operators.

a = b * 2;
  • 2 is a literal value expression.
  • b is a variable expression, which means to retrieve its current value.
  • b * 2 is an arithmetic expression, which means to do the multiplication.
  • a = b * 2 is an assignment expression, which means to assign the result of the b * 2 expression to the variable a.

3. I/O

I/O means input and output. Input receives the information from the user. Output typically means we can write the result to the console or file.

console.log() a output function which is used to print the text in the developer console.

console.log("Hello world");

a = 2;
console.log(a);

prompt() is a input function which pops a console and ask the user to input a name. The user name is store in a variable "name".

name = prompt("What is your name: ");

console.log(name);

4. Operators:

Operators are how we perform actions on variables and values.

a = 2;
b = a + 1;

We assign the 2 value to the a variable. Then, we get the value of the a variable(still 2 ), add 1 to it resulting in the value 3 , then store that value in the b variable.

you'll need the keyword var in every program, as it's the primary way you declare variables.

var a = 20;
a = a * 3;

console.log(a);

You should always declare the variable by name before you use it. But you only need to declare a variable once for each scope.


Reference

[1] Kyle Simpson, You Don't Know JS Series, O'Reilly Media (2014)

留言

熱門文章