Eloquent JavaScript - Chapter 2 - Program Structure (Notes)

octopus

Eloquent JavaScript(The Annotated Version) - Chapter 2 - Program Structure

Expressions and statements

an expression is a sentence fragment, a JavaScript statement is a full sentence in a human language.

“Expression” is:

  1. simply values
  2. made some values and then applied operatros to them to get new values.
  3. An expression between parentheses
  4. a binary operator applied to two expressions
  5. a unary operator applied to one expression

“Statement” is:

  1. an expression -> a sentence fragment
    a JavaScript statement -> a full sentence in a human language.
  2. A program is simply a list of statements.

Recommending that every statement needs a semicolon will always be terminated by one.

Variables

The special word (keyword) var indicates that this sentence is going to define a variable. It is followed by the name of the variable and, if we want to immediately give it a value, by an = operator and an expression.

Naming Variables:

  1. Variable names can be any word that isn’t a reserved word (such as var).
  2. Digits can also be part of variable names, but the name must not start with a digit.
  3. Variable names no punctuation, except for $ and _.

Variables vs Values:

  1. Variables do not contain values, variables refer to values.
  2. two variables can refer to the same values
  3. A program can access only the values that it still has a hold on via variables it contains.

you create a variable to grasp the value or you change the existing variable to grasp the value.

When you define a variable without giving it a value, If you ask for the value of an empty variable, you’ll get the value undefined.

Variable names are also case sensitive. So newVariable is not the same as NewVariable.

Keywords and reserved words

a number of words “reserved for use” in JavaScript world. Not allowed to 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

Reserved words in Douglas Crockford - The JavaScript Programming Language (Notes)

The environment

The collection of variables and their values that exist at a given time is called the environment.

Functions

Function is a type - a piece of program wrapped in a value.

  1. Executing a function is called invoking, calling, or applying it.
  2. You can call a function by putting parentheses after an expression that produces a function value.
  3. Usually you’ll directly use the name of the variable that holds the funciton.
  4. The values between the parentheses are given to the program inside the function.
    Values given to functions are called arguments.

The console.log function

Use console.log to output values.
why contain period characters?
We will find out exactly what this means in Chapter 4.

Return values

When a function produces a value, it is said to return that value.
Anything that produces a value is an expression in JavaScript, which means function calls can be used within larger expressions.

The next chapter(chapter 3) explains how to write your own functions.

Prompt and Confirm

confirm("Shall we, then?");
prompt("Tell me everything you know.", "...");

Control flow

More than one statement are executed from top to bottom.

Conditional execution

if (...)
....
else if (...)
....
else
....

While and do loops

while (...) {
...
}
do {
...
}
while (...)

Indenting Code

To make the structure of the code stand out

For loops

var result = 1;
for (var counter = 0; counter < 10; counter = counter + 1)
{
result = result * 2;
}

console.log(result);

Breaking Out of a Loop

break and continue

Updating variables succinctly

+=
*=
-=
++
--

Dispatching on a value with 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;
}

Capitalization

Camel Case and Pascal Case in Chapter 6.

Comments

// slash slash

/*
slash star
star slash
*/

Exercises

1.Write a loop that makes seven calls to console.log to output the following triangle:

#
##
###
####
#####
######
#######
for (var line = "#"; line.length < 8; line += "#")
console.log(line);

My solution

for(i = 1; i < 8; i++)
{
var j = 0;
var wall = "";

while (j < i)
{
wall += "#";
j++
}
console.log(wall);
console.log("\n");
}

2.FizzBuzz

Write a program that uses console.log to print all the numbers from 1 to 100, with two exceptions. For numbers divisible by 3, print “Fizz” instead of the number, and for numbers divisible by 5 (and not 3), print “Buzz” instead.

When you have that working, modify your program to print “FizzBuzz”, for numbers that are divisible by both 3 and 5 (and still print “Fizz” or “Buzz” for numbers divisible by only one of those).

(This is actually an interview question that has been claimed to weed out a significant percentage of programmer candidates. So if you solved it, you’re now allowed to feel good about yourself.)

for (var n = 1; n <= 100; n++) {
var output = "";
if (n % 3 == 0)
output += "Fizz";
if (n % 5 == 0)
output += "Buzz";
console.log(output || n);
}

Paul Irish’s solution

for (var i = 1; i <= 100; i++) {
  var f = i % 3 == 0, b = i % 5 == 0;
  console.log(f ? b ? "FizzBuzz" : "Fizz" : b ? "Buzz" : i);
}

My solution

for (i = 1; i < 101; i++) {
if (i%3 == 0 && i%5 == 0) {
console.log("FizzBuzz");
continue;
}

if (i%3 == 0) {
console.log("Fizz");
}
else if (i%5 == 0) {
console.log("Buzz");
}
else {
console.log(i);
}
}

3.Write a program that creates a string that represents an 8×8 grid, using newline characters to separate lines. At each position of the grid there is either a space or a “#” character. The characters should form a chess board.

Passing this string to console.log should show something like this:

 # # # #
# # # #
 # # # #
# # # #
 # # # #
# # # #
 # # # #
# # # #

When you have a program that generates this pattern, define a variable size = 8 and change the program so that it works for any size, outputting a grid of the given width and height.

var size = 8;

var board = "";

for (var y = 0; y < size; y++) {
for (var x = 0; x < size; x++) {
if ((x + y) % 2 == 0)
board += " ";
else
board += "#";
}
board += "\n";
}

console.log(board);