Eloquent Javascript Chapter 2
Program Structure
Expressions and statements
A fragment of code that produces a value is called an expression.
The simplest kind of statement is
an expression with a semicolon after it.
> 1;
> !false;
It is a useless program, though.
1 and true get thrown away.
Variables
To catch and hold values, JavaScript provides a thing called a variable.
> var caught = 5 * 5;
The special word (keyword) var indicates that this is going to define a variable.
After a variable has been defined,
it can be used as an expression
> var ten = 10;
> ten * ten
< 100
Variables
Variable name rules:
- Cannot be reserved keywords. i.e. (var)
- Cannot have spaces
- May have digits as long as it's not the first character (catch22)
- Cannot have punctuation except $ and _
Variables can be changed using the = operator.
var mood = "light";
console.log(mood);
// → light
mood = "dark";
console.log(mood);
// → dark
Variables
A variable without a value will be set to undefined.
var nothing;
console.log(nothing);
// → undefined
var one = 1, two = 2;
console.log(one + two);
// → 3
A single var statement may define multiple variables.
The definitions must be separated by commas.
Keywords and reserved words
Words with a special meaning, such as var, are keywords, and they may not be used as variable names.
break case catch class const continue debugger
default delete do else enum export extends false
finally for function if implements import in
instanceof interface let new null package private
protected public return static super switch this
throw true try typeof var void while with yield
Environment
The collection of variables and their values that exist at a given time is called the environment.
When a program starts up,
this environment is not empty.
For example, the browser environment that loads javascript will have a variety of global variables such as window.
Functions
A function is a piece of program wrapped in a value.
alert("Good morning!");
Many of the values that exist in the environment have the type function.
Executing a function is called invoking, calling, or applying it.
You can call a function by putting parentheses after an expression that produces a function value.
Functions
var x = 30;
console.log("the value of x is", x);
// → the value of x is 30
console.log
Most JavaScript systems (including all modern web browsers and Node.js) provide a console.log function that writes out its arguments to some text output device
Notice console.log has a period in the middle of it. console.log is actually an expression that retrieves the log property from the value held by the console variable.
Return values
console.log(Math.max(2, 4));
// → 4
console.log(Math.min(2, 4) + 100);
// → 102
Functions may also produce values.
When a function produces a value, it is said to return that value
Control flow
var theNumber = Number(prompt("Pick a number", ""));
alert("Your number is the square root of " +
theNumber * theNumber);
When your program contains more than one statement, the statements are executed, predictably, from top to bottom.
This is an example of straight control flow.
Conditional execution If
var theNumber = Number(prompt("Pick a number", ""));
if (!isNaN(theNumber))
alert("Your number is the square root of " +
theNumber * theNumber);
Conditional execution is written with the if keyword. This is used if there is code that we want only executed if, and only if a certain condition holds.
Conditional execution if/else
var theNumber = Number(prompt("Pick a number", ""));
if (!isNaN(theNumber))
alert("Your number is the square root of " +
theNumber * theNumber);
else
alert("Hey. Why didn't you give me a number?");
You often won’t just have code that executes when a condition holds true, but also code that handles the other case.
Conditional execution
if/else if/else
var num = Number(prompt("Pick a number", "0"));
if (num < 10)
alert("Small");
else if (num < 100)
alert("Medium");
else
alert("Large");
If we have more than two paths to choose from, multiple if/else pairs can be “chained” together
while loop
var number = 0;
while (number <= 12) {
console.log(number);
number = number + 2;
}
// → 0
// → 2
// … etcetera
while loops check the conditional and then execute the code.
do loop
do {
var yourName = prompt("Who are you?");
} while (!yourName);
console.log(yourName);
do loops execute first and then check the conditional.
for loop
for (var number = 0; number <= 12; number = number + 2) {
console.log(number);
}
// → 0
// → 2
// … etcetera
- The part before the first semicolon initializes the loop, usually by defining a variable.
- The second part is the expression that checks whether the loop must continue.
- The final part updates the state of the loop after every iteration.
Breaking out of a loop
- break : Allow the stop of a the loop
- continue : Jump out of the loop body and execute the loop again.
switch
switch (prompt("What is the weather like?")) {
case "rainy":
console.log("Remember to bring an umbrella.");
break;
case "sunny":
console.log("Dress lightly.");
case "cloudy":
console.log("Go outside.");
break;
default:
console.log("Unknown weather type!");
break;
}
Sometimes you will need many if else/if statements.
The switch statement solves this problem.
Each case must use a break in order to not fall through to the next case statement.
default will get run if none of the case statements match the conditional.
Comments
// This is a comment and ignored by the computer
var accountBalance = calculateBalance(account);
/*
This is also a comment ignored by the computer
but can be multiline
*/
Comments are often used to convey information that the code may not be able to.
Summary of Chapter 2
- A program is built out of statements.
- Statements tend to contain expressions.
- A program is executed from top to bottom.
-
Flow of control by using:
- conditional (if, else, and switch) and
- looping (while, do, and for) statements
- Variables can file pieces of data under a name.
- Functions are special values that encapsulate a piece of program.
- You can invoke them by writing functionName(argument1, argument2).
- Such a function call is an expression, and may produce a value.
Thank You
Eloquent Javascript Chapter 2
By Dustin McCraw
Eloquent Javascript Chapter 2
- 1,395