Skip to main content

Expressions and statements 21


A fragment of code that produces a value is called an expression. Every value written literally is also an expression - "dog" or 49 are expressions.

This is a Javascript program:

1;
!false;

Semicolons are optional. Use them until you figure out when to not use them.

Bindings 22


Bindings are variables. You don't actually create variables, you name a memory space something recognizable.

let caught = 5 * 5; The keyword "let" indicates that this sentence is going to define a binding, it is then followed by the name of the binding "caught" and then the value 5 * 5 is attached to it.

It doesn't mean that the value is attached to that binding forever:

let mood = "angry";
mood = "happy;
console.log(mood);

Bindings don't contain values, they grasp values - two bindings can have the same value.

If you ask for the value of an empty binding, you get "undefined"

Var and const can be used to create bindings - don't use var anymore.

  • const is used for non changing bindings

Binding names 24


Can't use one of these:

 break case catch class const continue debugger default
delete do else enum export extends false finally for
function if implements import interface in instanceof let
new package private protected public return static super
switch this throw true try typeof var void while with yield

The environment 24


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

Functions 24


Some values in the environment are called functions - it is an entire piece of code wrapped in a value

You use a function by calling, invoking, or applying the function

let user = functionName(Steve);

The entire code in the function might be to search a directory for the first name Steve.

Values given to functions are called arguments

The console.log function 25


This is a function: console.log(); The period in the function name isn't just for show, it separates the name of the binding, "console" and the method ".log()" on that binding.

Return values 25


When a function produces a value, it is said to return that value.

function addNumbers(a,b) {
return a + b;
}

Control flow 26


Your code is executed from the top of your file down

  • could be a straight line, could be a loop or a branched path. It does execute from the top down, though.

Conditional execution 26


This is when the code doesn't follow a straight line - if this, then do this and then repeat that a lot.

let theNumber = Number(3);
if (!Number.isNaN(theNumber)) {
console.log("Your number is the square root of " + theNumber * theNumber);
}

let theNumberBad = Number("dog");
if (!Number.isNaN(theNumberBad)) {
console.log("Your number is the square root of " + theNumber * theNumber);
} else {
console.log(`${theNumberBad} is not a number at all.`);
}

The statement after if is wrapped in a block of 's

If Else


You can add else statements to provide an if this, or do this type logic. See the code block above for an example.

while and do loops 28


These are used to repeat tasks until a certain condition exists.

  • Write all even numbers from 0 to 100

The while loop checks to see if it should stop, then executes The do loop executes a statement first, then checks whether it should stop

While:

let number = 0;
while (number <= 100) {
console.log(number);
number = number + 2;
}
// → 0
// → 2
// .. etc

Do:

let yourName;
do {
yourName = prompt("Who are you?");
} while (!yourName);
console.log("Hello " + yourName);

Indenting Code 30


2 spaces or 4 spaces. I use prettier to format and set it to 2 spaces. image.png

The "render whitespace" option may be useful here.

for loops 31


For loops follow the while loop example.

for (let number = 0; number <= 12; number = number + 2) {
console.log(number);
}
// → 0
// → 2
// .. etc

The format of a for loop is (Initialization;check;update)

Breaking Out of a Loop 32


Satisfying the condition of the loop is not the only way to escape it. You could be incrementing numbers and once the number is 8, break out of the loop. Or, in a lot of cases: %

Break or continue is typically used.

Infinite loops are loops that never have a way to escape it.

while(true) {
//do stuff
}

Updating bindings succinctly 32


counter = counter + 1;
// can be shortened to
counter += 1;
//or
counter ++;

//or another example:
for (let number = 0; number <= 12; number += 2) {
32
console.log(number);
}

Dispatching on a value with switch 33


A switch statement in some ways is an alternative to a lot of if else statements

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 34


Use camelCase not PascalCase or snake_case or kebab-case

Comments 34


Comments can be identified as

// this is a comment
console.log("happy!");
/*
this is also a comment
*/

Summary 35


You now know that a program is built out of statements, which themselves sometimes contain more statements. Statements tend to contain expressions, which themselves can be built out of smaller expressions. Putting statements after one another gives you a program that is executed from top to bottom. You can introduce disturbances in the flow of control by using conditional (if, else, and switch) and looping (while, do, and for) statements. Bindings can be used to file pieces of data under a name, and they are useful for tracking state in your program. The environment is the set of bindings that are defined. JavaScript systems always put a number of useful standard bindings into your environment. 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

Exercises 35


  • Looping a triangle
let triangle = "#";
while (triangle.length < 8) {
console.log(triangle);
triangle += "#";
}
  • FizzBuzz
let number = 0;
while (number < 101) {
if (number % 3 === 0 && number % 5 === 0) {
console.log(`${number}: FizzBuzz`);
} else if (number % 3 === 0) {
console.log(`${number}: Fizz`);
} else if (number % 5 === 0) {
console.log(`${number}: Buzz`);
} else {
console.log(number);
}
number++;
}

// more advanced method:
for (let i = 0; i < 100; )
console.log((++i % 3 ? "" : "Fizz") + (i % 5 ? "" : "Buzz") || i)

This does two things differently

  • doesn't increment inside the for loop
  • uses ternary operator chaining.

Chessboard


let size = 8;
let x = 0;
while (x < size) {
if (x % 2 === 0) {
console.log("# # # #");
} else {
console.log(" # # # #");
}
x++;
}

This prints the chessboard with a static size = 8, but not the width. We can change the size to any number and will increase all of the rows.

Here's my solution, albeit doesn't use the new line \n:

let size = 64;
let x = 0;
while (x < size) {
if (x % 2 === 0) {
let y = " ";
while (y.length < size) {
y += "X ";
}
console.log(y);
} else {
let y = "X";
while (y.length < size - 1) {
y += " X";
}
console.log(y);
}
x++;
}