JavaScript from Scratch - Hello JavaScript | Programming Fundamentals: Learn to program with JavaScript (2016)

Hello JavaScript | Programming Fundamentals: Learn to program with JavaScript (2016)

JavaScript from Scratch

JavaScript from ScratchJavaScript from Scratch

I think everyone should learn how to program a computer, because it teaches you how to think. I view computer science as a liberal art, something everyone should learn to do. - Steve Jobs

Congratulations! At this point you should be fairly comfortable with creating a program using flow charts or pseudo code. Unfortunately, JavaScript does not convert flowcharts or pseudo code to actual code. Maybe it will sometime in the future. Don’t worry. The skills that you picked up in the last chapter can be carried on to any language. In this chapter, we will be taking a look at how we can implement those programming fundamentals specifically in JavaScript.

From this section you should expect a translation of all the flowcharts and pseudo code covered in the previous section.

At the end of the chapter you will be required to solve another problem set, but this time flowcharts and pseudo code won’t be good enough. They can be used, but the end solution must be valid, executable code.

What exactly is JavaScript?

JavaScript, also known as ECMAScript, is a cross-platform, multi-paradigm, dynamic programming language. It is a small and lightweight language. JavaScript can be connected to the objects of its host environment to asynchronously provide programmatic control over them.

JavaScript is NOT Java. If you later decide to move on to program with Java, you can take with you the concepts that you learned in the Expressive Programming chapter.

The programming language JavaScript was originally designed and created in 10 days on May 1995 by Brendan Eich. The language was created to run on a browser named Netscape, later renamed Mozilla. The purpose of the language was to allow new programmers to easily create new programs, making JavaScript a very fluid and easy language to get started programming with.

What is ECMAScript? ECMA(European Computer Manufacturers Association) is a non-profit organization that originally created the standard specification for ECMAScript. JavaScript is an implementation of that standard.

What is ActionScript 3? ActionScript 3 is an implementation of the ECMAScript standard. Although the language itself is used to develop software applications for Adobe Flash Player, it resembles that of JavaScript.

What about ES6? ES6, also known as ECMAScript 6, is another iteration of the ECMAScript standard that provides a much simpler and clearer syntax. As of this writing, ES6 is released but not yet supported across all platforms. ES5 is what’s used throughout this book. ES6 has full backward support for ES5.

Examples use cases of JavaScript

Client-side JavaScript extends the core language by supplying objects to control a browser and its Document Object Model (DOM). For example, client-side extensions allow an application to place elements on an HTML form and respond to user events such as mouse clicks, form input, and page navigation.

Server-side JavaScript extends the core language by supplying objects relevant to running JavaScript on a server. For example, server-side extensions allow an application to communicate with a database, provide continuity of information from one invocation of the application to another, or perform file manipulations on a server.

JavaScript is entering a completely new and exciting cycle of evolution, innovation, and standardization. With new developments in platforms such as Node.js, we can now use JavaScript on the server-side and HTML5 APIs to control user media, open up web sockets for always-on communication, get data on geographical location and device features such as accelerometer, and so much more. It is an exciting time to learn JavaScript!

Let’s start making the computer answer all of our commands

Sugar Syntax

Every programming language needs a specific syntax, and JavaScript is no exception to this. Syntax can be thought of as the punctuation and grammar of the actual statements being written. Just like written languages, this can be a highly opinionated subject, but I will try my absolute best to show you examples of what you will encounter in your career as a JavaScript programmer.

JavaScript is very forgiving in the syntactic correctness of your statements, but don’t take this too lightly. Other programmers will be reading your code, so it’s best to be as clear as possible. You can have a perfectly syntactic, valid program and it still not work the way you want it to. This is due to not having the right semantics. You will soon find out that it’s easy to create syntactic, valid programs but not semantic programs.

Case Sensitive

JavaScript’s interpreter can distinguish between uppercase and lowercase letters. Typically what you will find in most programs is camel-cased variables, functions, and classes.

Comments

Code comments are a valuable tool that you can use to make your code more readable and understandable in certain cases. Comments are great, but you should give your code the ability to speak for itself, meaning that comments should only be used when you know exactly what message you want to deliver to the reader, another human being. Some situations where comments might be useful could include specific cases, documentation for a piece of code, or explaining complex logic. Documentation needs to be written at a higher level of abstraction that communicates to the reader the intention of the code and what post- and pre-conditions are expected when executing that specific part of the code.

Single-Line Comment: Single line comments start with // and end at the line break.

Code Example

1 // The code below shows a single line of code with a comment

2 'one line comment'; // This entire line will be ignored

Multi-Line Comment: Multiple line comments, start with /* and end with */.

Code Example

1 /*

2 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam non diam ante.

3 Phasellus at quam vitae sapien porta egestas vel eu lorem.

4 Duis viverra lectus eget nisi placerat, et scelerisque felis suscipit.

5 Morbi faucibus eu urna ut laoreet. Nullam condimentum rutrum sem.

6 Hendrerit accumsan sed vitae ante.

7 */

In-Line Comment: Having a comment with in a line of code can be useful at times.

Code Example

1 (10 % /* Even Number */ 2 == 0);

TODO: As a new programmer you might encounter a TODO:, in this book or in a piece of code from an online repository. The purpose of a TODO: is to create a task or set a reminder to improve the code in one way or another.

You will typically see it written in this form.

Code Example

1 // TODO: Improve this code

2 // ....

3 // ....

4 // ....

Code Example

1 // TODO: don't have any special purpose.

2 // You could easily use something else.

3 // By convention TODO: is what you will typically find.

Pro Tip

Some text editors support the ability to be able to quickly jump to a specific TODO: in a file.

Semicolons

Semicolons are optional in JavaScript. It’s considered best practice to have a semicolon after each statement. In later sections we will see how semicolons are used throughout a program.

Statements

Statements are multiple evaluations that are combined to create a program.

Code Example

1 (10 % /* Even Number */ 2 == 0);

2 32 + 72;

3 "Ferguson" + " " + "Jones";

This program does very little—it just evaluates multiple values. It does not display or affect anything else. If you wish to run the program, you will find that you end up with no output.

Special Tokens

JavaScript uses special characters that are reserved for creating source code. Below is a list of the most common symbols that you will encounter.

Tokens

Don’t worry too much about exactly what each of these symbols do. We will explore this in a later section.

Representing Scope

Using flowcharts, we were able to represent scope by inserting a shape inside another shape. In JavaScript, we can do the exact same thing by using the open and close curly braces {}.

ScopeCode Example

1 if(number > nextNumber){

2 // TODO: swap numbers

3 }

Again, don’t worry about the if statement. It’s covered in more detail in the Control Structures section. Make a note of the open and close curly braces {} . They represent the start and stop of the scope. Although JavaScript does not require them for a single line of code, it is best practice to add them because it keeps your code clear and concise.

Syntax Questions


Are indentations or white spaces required? Indentations are optional. You can use spaces, tabs, or nothing at all. Although it’s highly recommended that you have them in order to make sense of your program. In the examples that are provided in the book you will encounter indented code. The indentations are used to clarify scope, define different blocks of code, and have overall maintainable code.

Console

When programming in a specific environment, you will automatically inherit the abilities of that environment. The interpreter Node.js will provide you with the most common functionality that your program might need. Some abilities include getting input from a user, reading files, writing files, and displaying values on the screen, but that’s beyond this scope of this book.

One of the functionalities that Node.js provides is the ability to display a value on the screen. The way that Node.js does this is by invoking a function that is part of the Node.js API.

I/O | Input or Output: Represents data input or output from a process.

Flow Chart

OutputPseudo Code Example

1 name = ferguson

2 display the name

Code Example

1 var name = "Ferguson";

2 console.log(name);

From the example above you can see that we use a variable named console and then use the . notation to log the name. Don’t get too hung up on the syntax of how this is working. Just know that it works.

The console object differs from that of a regular variable by providing you with some new functionality. Here are a the most common uses of the console object:

Display Value

Code Example

1 var name = "Ferguson";

2 console.log(name); //Result -> Ferguson

Display Value with a string

Code Example

1 var name = "Ferguson";

2 console.log("Name:", name); //Result -> Name: Ferguson

You can keep adding variables to the console.log to keep displaying them, for N number of items.

Code Example

1 var name = "Ferguson";

2 var age = 21;

3 console.log("Name:", name, "Age:", age); //Result -> Name: Ferguson Age: 21

Don’t worry if all of this does not make perfect sense. Just know that you can now display the results of your program on the screen. In a later section we will explore in more detail how exactly console.log() works.

Variables

JavaScript is a loosely typed language. There is no need to explicitly declare the type of data that the variable will be holding. This means that, with JavaScript, a variable is a value that can change depending on the conditions that you set for it in your program. If you remember back to your algebra studies, a variable can hold any kind of value and that value can change depending on the conditions of the problem. The same applies to programming.

Variable Preparation: Stores a preparation measure before defining a process.

Flow Chart

PreparationPseudo Code

1 name = "Becky"

JavaScript Code Translation

1 var name = "Becky";

Naming Conventions Naming conventions for variables are strict. They can be any word that does not start with a number or a special character except ($, _,.). When creating variable, name keep in mind the best practice covered in the Key Concepts section.

Case Sensitivity: Variables are case sensitive. For example, if you have two variables that are exactly the same word but have different cases, they are different variables.

Non-Space Sensitivity: Spaces do not matter in your programs. You typically only add spaces for readability. The Node.js interpreter does not care if you have spaces or not. There are even specific tools that you can use to remove all white spaces from your program to obtain a minifiedversion.

JavaScript Code Sample

1 var name = "Becky";

2 var Name = "Robert";

3 console.log(name); //Result -> Becky

4 console.log(Name); //Result -> Robert

Semicolons

Semicolons are highly controversial. JavaScript is very flexible and forgiving in this manner.

JavaScript Code Sample

1 var firstName = 'Isabella' // BAD

The code is perfectly valid, but it’s always best to tell JavaScript when a statement ends by using the ; at the end of the statement.

JavaScript Code Sample

1 var firstName = 'Isabella'; // best practice

If you want to create two variables; for example, firstName and lastName, simply use two variables.

JavaScript Code Sample

1 // best practice

2 var firstName = 'Isabella';

3 var lastName = 'Ramirez';

4 /* OR */

5 var firstName = 'Isabella', // <---- use the comma to separate variable names

6 lastName = 'Ramirez';

Warning

New programers might tend to make the mistake of creating two variables on the same line.

JavaScript Code Sample

1 var firstName = 'Isabella' var lastName = 'Ramirez' // WRONG will not execute

That might seem like it is perfectly good code, it’s just missing the semicolon ; at the end. If you add the semicolon at the end of firstName, the code will run. This is because the JavaScript interpreter will add the semicolon at the end of the line automatically. Don’t trust or count on this happening every time. It’s best to split the code into separate lines and provide semicolons.

Data Types

Data Types

Primitives

Type

Description

Examples

Numbers

Numerical representation of a values

1,7,13,19,3.14,0.99923

Strings

Sequence of characters composing a string

"Becky Anderson" or 'Becky'

Booleans

True or False value

True or False

null

Declared but does not yet have a value

null

undefined

Represent no value

undefined

Numbers

JavaScript has only one type of number of type called number. You can represent numbers in four different ways. Don’t overthink the usage of the numbers. For example, infinity and NaN might not work like you intend. All numbers are stored in a 64-bit floating point. That means that whole numbers up to 15 digits are accurate, but decimal number representations are considered approximations.

Number Types

Example

Whole Number Value

32

Decimals Value

32.333333

Infinity Value

Infinity

NaN value

NaN

Whole Numbers also known as Integers

JavaScript Code Sample

1 var number = 1000;

2 console.log(number); //Result -> 1000

Decimal Number

JavaScript Code Sample

1 var number = 1000.9999;

2 console.log(number); //Result -> 1000.9999

Infinity Number

JavaScript Code Sample

1 var number = Infinity;

2 console.log(Infinity); //Result -> Infinity

NaN Number

JavaScript Code Sample

1 var number = NaN;

2 console.log(NaN); //Result -> NaN

Strings

The datatype String can hold a value of type string. The strings syntax states that the string must start with either a single quote or double quote. Whichever one starts the string must also end it.

JavaScript Code Sample

1 var firstName = 'Brandi';

2 var lastName = "Rodriguez";

3 console.log(firstName); //Result -> Brandi

4 console.log(lastName); //Result -> Rodriguez Rodriguez

Some of your programs might require you to convert a string to a certain format. JavaScript provides the escape character \ to exclude parts of a string and turn them into special characters. This is handy for when you want to put a double quote in your string without ending it, as well as similar cases.

The escape characters are the following.

Type

Description

\'

single quote

\"

double quote

\\

backslash

\n

new line

\t

tab

\b

backspace

\f

form feed

JavaScript Code Sample

1 var user = 'Account:\t123\nName:\tBrandi Rodriguez\nNick Name:\t\'@Brandii91\'';

2 console.log(user);

3 /* Result ->

4 Account: 123

5 Name: Brandi Rodriguez

6 Nick Name: '@Brandii91'

7 */

Strings do not work the same way that numbers do. The only exception to this is the concatenate process. When you add two or more strings you end up with a single linked string.

JavaScript Code Sample

1 var firstName = 'Brandi';

2 var lastName = "Rodriguez";

3 var fullName = firstName + ' ' + lastName;

4 console.log(fullName); //Result -> Brandi Rodriguez

In the Beyond The Basics chapter, we take a closer look at how we can mutate strings to different forms.

Booleans

A boolean can either be true or false. You can create Booleans by an evaluation or a simple true or false value. If it’s as simple as a true or false value it must be all lowercase. For example, TRUE will not work but true will.

JavaScript Code Sample

1 var activeAccount = true;

2 console.log(activeAccount); //Result -> true

3 console.log(10 < 3); //Result -> false

null

null represents a value that is empty; it holds no value. You will find nulls when you explicitly don’t want to have a value on a variable.

JavaScript Code Sample

1 var name = "Brandi";

2 /* Brandi is not feeling so good */

3 /* NULL her out! */

4 name = null;

5 console.log(name); //Result -> null

undefined

undefined represents a value that is meaningless; it holds no value. undefined is typically found in variables that are declared but contain no value.

JavaScript Code Sample

1 var name;

2 console.log(name); //Result -> undefined

Undefined vs Null: Undefined means that the variable has been declared but does not yet have a value. Null, on the other hand, is set to a variable to represent no value.

Composites

Type

Description

Examples

Arrays

A container that holds values

var items = [123,32,12.0,'becky',22]

Objects and Functions are considered composites but not covered in this chapter, but arrays are. Make a quick note of the [] bracket token notation being used to create one as you will need to know it for when we explore arrays in more detail in the array section.

Operators

Now that we can create primitive and composite data types, it’s important to be able to test for a certain data type. This is important; for example, your program might require a number but get a string as inout. Here is where you can use a control structure to evaluate that value using thetypeof operator.

JavaScript Code Sample

1 var firstName = 'Brandi';

2 var account = '1234';

3 var age = 21;

4 var accountActive = false;

5 var password = null;

6

7 console.log(typeof firstName); //Result -> string

8 console.log(typeof account); //Result -> string

9 console.log(typeof age); //Result -> number

10 console.log(typeof accountActive); //Result -> boolean

11 console.log(typeof password); //Result -> null

Math & Logical Expressions

Arithmetic: Just like in math, computers can operate on two or more numbers. If you recall from your algebra knowledge, multiple operations can be made on a set of numbers. Below you will find examples of each of these operators.

Operator

Description

+

Addition

-

Subtraction

*

Multiplication

/

Division

%

Modulo

Addition

JavaScript Code Sample

1 var value = 3 + 3;

2 console.log(value); // Result 6

Subtraction

JavaScript Code Sample

1 var value = 3 - 3;

2 console.log(value); // Result 0

Multiplication

JavaScript Code Sample

1 var value = 3 * 3;

2 console.log(value); // Result 9

Division

JavaScript Code Sample

1 var value = 3 / 3;

2 console.log(value); // Result 1

Modulo The modulo is used to represent the remainder of two numbers. Modulus was omitted from the key concepts section due to other languages representing the modulo as a different symbol. JavaScript strictly uses the % symbol.

JavaScript Code Sample

1 var value = 3 % 3;

2 console.log(value); // Result 0

Logical Expressions

All logical expressions must evaluate to a boolean value. A logical expression is composed from a logical operator. Multiple operators can be combined to evaluate multiple values.

Operator

Description

==

Equal to

!=

Not equal

>

Greater than

>=

Greater than or equal to

<

Less than

<=

Less than or equal to

Control Structure

Single if statement

BranchJavaScript Code Sample

1 if(condition){

2 // True Branch

3 }

Ternary Operator

The conditional (?:) ternary operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement.

Syntax Example:

JavaScript Code Sample

1 (condition ? expression1 : expression2)

2 (true or false ? true condition : false condition )

Condition is an expression that evaluates to true or false. expression1, expression2 expressions with values of any type.

Nested if statements

BranchJavaScript Code Sample

1 if(condition){

2 // True Branch

3 if(condition){

4 // True Branch

5 }

6 }

if else statements

BranchJavaScript Code Sample

1 if(condition){

2 // True Branch

3 }else{

4 // False Branch

5 }

Nested if else statements

BranchJavaScript Code Sample

1 if(condition){

2 // True Branch

3 if(condition){

4 // True Branch

5 }else{

6 // False Branch

7 }

8 }else{

9 // False Branch

10 if(condition){

11 // True Branch

12 }else{

13 // False Branch

14 }

15 }

if else if else statements

BranchJavaScript Code Sample

1 if(condition){

2 // True Branch

3 }else if(condition){

4 // True Branch

5 }else{

6 // False Branch

7 }

Chained if else if statements

BranchJavaScript Code Sample

1 if(condition){

2 // True Branch

3 }else if(condition){

4 // True Branch

5 }else if(condition){

6 // True Branch

7 }else if(condition){

8 // True Branch

9 }else if(condition){

10 // True Branch

11 }

Switch statement

Branch

The switch statement evaluates an expression, matches the expression’s value to a case clause, and executes the statements associated with that case.

JavaScript Code Sample

1 switch (condition) {

2 case condition:

3 /* True branch */

4 /* True branch */

5 break;

6 case condition:

7 /* True branch */

8 /* True branch */

9 break;

10 case condition:

11 /* True branch */

12 /* True branch */

13 break;

14 case condition:

15 /* True branch */

16 /* True branch */

17 break;

18 case condition:

19 /* True branch */

20 /* True branch */

21 break;

22 default:

23 /* Default branch */

24 /* Default branch */

25 }

Expression: an expression matched against each case statements.

Case: a case used to match against expression.

Default: executed if expression does not match any case statements.

The difference between a switch statement and an if else statement is that in a switch statement, you can continue execution on multiple branches, whereas in the if statement, you must explicitly remain on the branch that evaluated to true.

JavaScript provides the keyword break to stop a switch statement. If the switch statement is omitted, the switch statement will fall through, meaning the next statement will execute.

Using break

BreakJavaScript Code Sample

1 switch (condition) {

2 case condition:

3 // True branch

4 break;

5 default:

6 // No need for a break here

7 }

Omitting the break statement

Fall ThroughJavaScript Code Sample

1 switch (condition) {

2 case condition:

3 // True branch

4 default:

5 // No need for a break here

6 // This will execute

7 }

Loops and Iteration

Loops and iteration help us to execute a piece of code repetitively. Loops and iteration differ in a couple of ways. JavaScript supports the following loop and iteration flows:

Keyword

Description

while

loops through a section of code while a specified condition is true

do while

loops through a section of code while a specified condition is true

for

iterates through a section of code N number of times

for in

iterates through a predefined number of items

Loops

while loop

The while loop’s condition is evaluated. If it evaluates to true, the loop will execute once and then check the condition again. This will continue until the condition becomes false or the break statement is used.

While LoopJavaScript Code Sample

1 while (condition) {

2 // Code statements go here

3 //...

4 //...

5 //...

6 //...

7 }

Pro Tip

Watch out for infinite loops, in general they are undesirable.

do while loop

Just like the while loop, this loop will loop through a piece of code. The do while loop does have a specific format that it must be typed in: the while keyword must be on the same line as the closing curly brace and have a semicolon at the end of the closing parentheses.

Do While LoopJavaScript Code Sample

1 do {

2 // Code statements go here

3 //...

4 //...

5 //...

6 //...

7 } while (condition); // <- NOTE the syntax

Pro Tip

The do while loop is guaranteed to execute, at least once.

Iteration

Iteration requires that you have a counter to keep track of what part of the iteration you are in and how much you have to go. Iteration helps you with iterating over a set of data when you know exactly how many items you need to iterate over.

for loop. The JavaScript for loop has three separate sections between the parentheses:

1. The initialization, only runs on the first iteration

2. The condition, runs on every iteration

3. Post iteration expression, runs at the end of each iteration

Each of these sections must be separated by a semicolon in order to be valid syntax.

For LoopJavaScript Code Sample

1 var iterations = 30;

2 for (var i = 1; i <= iterations; i = i + 1) {

3 console.log(i);

4 }

Results

1 1

2 2

3 ...

4 ...

5 29

6 30

The example creates a variable named iterations and sets it to 30. Inside the loop, the variable i is created and set to 1. The for iteration will check whether it should continue iterating or stop. The last part of the loop is to increment the count of i. The loop will stop when i becomes larger than 30.

Just as you can increment a count, you can also decrement a count.

JavaScript Code Sample

1 for (var iterations = 30; i < iterations >= 0; iterations = iterations - 1) {

2 console.log(iterations);

3 }

4 // Alternative syntax

5 var iterations = 30

6 for (; iterations >= 0; iterations = iterations - 1) {

7 console.log(iterations);

8 }

Results

1 30

2 29

3 ...

4 ...

5 1

6 0

The code displays a countdown from 30 to 0. It is best practice to set the definition of the counter inside the for loop.

Increment or Decrement Syntax

JavaScript supports multiple syntaxes to change the value of a counter. The most common ones are the following:

Pre-increment or Pre-decrement

1 var count = 0;

2 ++count;

3 --count;

Post-increment or Post-decrement

1 var count = 0;

2 count++;

3 count--;

Addition or subtraction

1 var count = 0;

2 count = count + 1;

3 count = count - 1;

Addition or subtraction short hand

1 count += 1;

2 count -= 1;

Difference Between Pre- and Post-? There is a slight performance increase when you pre-increment or pre-decrement a counter thanks to how JavaScript evaluates the expression.

What about Different Operators? All arithmetic operators are supported, but the most common are increment and decrement.

Early termination

Loops can be terminated early by using the break keyword. This is specifically useful for when you need to stop a loop without knowing the number of repetitions beforehand.

Early TerminationJavaScript Code Sample

1 var numberOfUsers = 300;

2 while (true) {

3 if(numberOfUsers == 249){

4 console.log('Go no further!');

5 break;

6 }else{

7 console.log(numberOfUsers);

8 numberOfUsers = numberOfUsers - 1;

9 }

10 }

Results

1 300

2 299

3 298

4 ...

5 ...

6 251

7 250

8 Go no further!

The code above is in an infinite loop. The code prints out the first 50 numbers preceding 300 in reverse order. When it gets to 249, it displays the message Go no further! instead, then terminates using the break keyword.

How does Node.js REPL Work?

The REPL(read–eval–print loop) can be accessed on your machine by using the node command on your terminal.

How exactly does REPL work?

1. Reads the code that you provide

2. Evaluates the code

3. Outputs the result, if any.

4. Goes back to step 1.

The REPL loop will evaluate any code, no matter how complicated, process that code, and then go back to step one ready to take new requests. This is also known as a program that is in an infinite loop.

Arrays

Arrays

Arrays are the first composite data type that we will be taking a look at. Arrays are not a primitive type. Arrays are considered a data structure, which is just a way of defining how information is stored in memory. Our programs up to this point have used variables, and many of them. At times some of the programs that you create they will require more than a handful of variables, and this is where arrays are most commonly used. Arrays allow you to group a set of variables into a single data structure and have just one variable to contain multiple variables or values in memory.

An array is an ordered collection of data (either primitive or objects). Based on its place in the array, each data item has a numeric index through which you can access the corresponding value. In JavaScript, arrays are also objects that have their own properties.

Arrays can be created with the [] bracket notation.

JavaScript will allow you to add any data type to an array, but first you must declare an array with a given name. The most common names that you will find in an array would be a plural name, for example instead of having firstName you would have firstNames. This is typically used to show that the array has more than one item. Each of the items in the array must be separated by a comma ,.

Example of declaring an array

1 var firstNames = ['Becky', 'Ferguson', 'Megan', 'Kimberly', 'Brandy']; // Array \

2 with items

3 var lastNames = []; // Empty Array

4 var ids = [21]; // Single item in array

5

6 console.log(firstNames);

7 console.log(lastNames);

8 console.log(ids);

Results

1 [ 'Becky', 'Ferguson', 'Megan', 'Kimberly', 'Brandy' ]

2 []

3 [ 21 ]

JavaScript allows you to have mixed datatypes in an array.

JavaScript Code Sample

1 var ages = ['Twenty One', 'Eighteen', 19, 22]; // Array with ages

2 console.log(ages);

Results

1 [ 'Twenty One', 'Eighteen', 19, 22 ]

Result

In JavaScript, all arrays start their indices at 0 and end at one less than the size of the array.

Array Indexes

In the example above, the array is size 5 but the indexes range from 0 to 4. Each value of an array can be accessed through a valid index.

Example of accessing a value with an index.

JavaScript Code Sample

1 var ids = [12,1,12,7,null];

2 console.log(ids[3]);

Results

1 7

How Do I Add a Variable to an Array? The example above sets the initial values of the array inside the bracket [] notation. This is just a quick way to create variables without a name. If you have a variable that needs to go in an array, you can simply add it to the array just as you would with a definition of a brand new value.

Example of adding a variable to an array

JavaScript Code Sample

1 var specialId = 32;

2 var ids = [12,1,12,7,specialId];

3 console.log(ids[4]);

Results

1 32

What If I Use an Invalid Index?: This is a common error that new programmers typically make—it even has a name. It is called an “off by one error”. In JavaScript, nothing major will happen. You will just access a place in memory that is undefined. In other languages, this can be a more serious issue.

JavaScript Code Sample

1 var ids = [12,1,12,7,null];

2 console.log(ids[5]);

Results

1 undefined

Arrays are used when you need to keep a large amount of data in memory at the same time.

This is a perfect example of what not to do.

Example of what NOT to do

1 // BAD CODE!!!!

2 // DONT DO THIS!!!

3 var becky = "Becky";

4 var ferguson = "Ferguson";

5 var megan = "Megan";

6 var kim = "Kimberly";

7 var brandy = "Brandy";

8

9 console.log(becky);

10 console.log(ferguson);

11 console.log(megan);

12 console.log(kim);

13 console.log(brandy);

Results

1 Becky

2 Ferguson

3 Megan

4 Kimberly

5 Brandy

Now instead of having five variables, all five names can now be stored in a single variable. The following example uses an array along with a for in loop to display the names.

JavaScript Code Sample

1 /* Much Cleaner */

2 var firstNames = ['Becky', 'Ferguson', 'Megan', 'Kimberly', 'Brandy'];

3 for (var index in firstNames) {

4 console.log(firstNames[index]);

5 }

Results

1 Becky

2 Ferguson

3 Megan

4 Kimberly

5 Brandy

Although both of the programs are valid, one of them is very rigid and hard to change and maintain. For example, if you had a list of 300 first names, would you create 300 variable names? Probably not! Remember, an array is a group of memory locations that contain data types that are grouped together.

You should use arrays when you know that your program is going to require a piece of data throughout the execution time of the program. Computers are slow to read and write from files, databases, or other locations. It’s always your best and fastest option to work with local variables.

Arrays can grow to be large data sets. How large? As much as your computer memory will allow.

Iterating over an array

Iterating over an array is the process of walking through the array based on an expression. You can use any of the loop or iteration keywords to go through an array. Arrays have different properties available, such as the length property.

while loop

JavaScript Code Sample

1 var firstNames = ['Becky', 'Ferguson', 'Megan', 'Kimberly', 'Brandy'];

2 var index = 0;

3 if(firstNames.length > 0){

4 /* Safe guard, just in case it's an empty array */

5 do {

6 console.log(firstNames[index]); // The value is looked up based on the value\

7 of the index

8 index++; // Post increment the index value

9 } while (index < firstNames.length);

10 }

do while loop

JavaScript Code Sample

1 var firstNames = ['Becky', 'Ferguson', 'Megan', 'Kimberly', 'Brandy'];

2 var index = 0;

3 while (index < firstNames.length) {

4 console.log(firstNames[index]); // The value is looked up based on the value o\

5 f the index

6 ++index; // Pre increment the index value

7 }

for loop

JavaScript Code Sample

1 var firstNames = ['Becky', 'Ferguson', 'Megan', 'Kimberly', 'Brandy'];

2 for (var index = 0; index < firstNames.length; index++) {

3 console.log(firstNames[index]); // The value is looked up based on the value o\

4 f the index

5 }

for in loop

JavaScript Code Sample

1 var firstNames = ['Becky', 'Ferguson', 'Megan', 'Kimberly', 'Brandy'];

2 for (var index in firstNames) {

3 console.log(firstNames[index]); // The for loop out puts the index, instead of\

4 the value

5 }

Pro Tip

The most common loop structure to iterate over an array is the for loop.

All of this programs output the same values

Results

1 Becky

2 Ferguson

3 Megan

4 Kimberly

5 Brandy

This process of iterating over the array is not just limited to going in sequential order from 0 up one less than the length of the array. Whatever expression you can create that evaluates to a valid index and terminates the loop will work. For example, you can also only display the indices that fall into an even number or iterate the array in reverse.

Only displaying even indexes.

1 var firstNames = ['Becky', 'Ferguson', 'Megan', 'Kimberly', 'Brandy'];

2 for (var index = 0; index < firstNames.length; index++) {

3 if(index % 2 == 0){ // This will be true at indexes 0, 2, and 4

4 console.log(firstNames[index]);

5 }

6 }

Results

1 Becky

2 Megan

3 Brandy

Iterating over an array in reverse

1 var firstNames = ['Becky', 'Ferguson', 'Megan', 'Kimberly', 'Brandy'];

2 for (var index = firstNames.length - 1; index > -1; index--) {

3 console.log(firstNames[index]);

4 }

Results

1 Brandy

2 Kimberly

3 Megan

4 Ferguson

5 Becky

Mutating Arrays

It’s great that we can iterate over an array, but some of our programs might require us to change the value of an item in the array. Take for example the following program. It will swap out the beginning of the array with the end of the array. In other words, it will reverse the array.

JavaScript Code Sample

1 var firstNames = ['Becky', 'Ferguson', 'Megan', 'Kimberly', 'Brandy'];

2 var startIndex = 0; /* Location of the first item */

3 var done = false;

4

5 for (var endIndex = firstNames.length - 1; endIndex > -1; endIndex--) {

6 if(startIndex == endIndex || done){

7 if(!done){

8 // We are at the middle, all done!

9 done = true;

10 }

11 console.log(firstNames[startIndex]);

12 startIndex++; // Continue iterating the rest of the array

13 }else{

14 var temp = firstNames[startIndex]; /* Hold this value while we swap out the \

15 values */

16 firstNames[startIndex] = firstNames[endIndex]; // Swap out the last item wit\

17 h the first item

18 firstNames[endIndex] = temp; // Swap out the first item with the last item

19 console.log(firstNames[startIndex]); // Display name

20 startIndex++; // Start iterating the array

21 }

22 }

Results

1 Brandy

2 Kimberly

3 Megan

4 Ferguson

5 Becky

Pro Tip

Remember when mutating an array the values of the array change.

Now, if you iterate through the array in sequential order you will get the reversed array instead of the original array.

JavaScript Code Sample

1 var firstNames = ['Becky', 'Ferguson', 'Megan', 'Kimberly', 'Brandy'];

2 var startIndex = 0; /* Location of the first item */

3 for (var endIndex = firstNames.length - 1; endIndex > -1; endIndex--) {

4 if(startIndex == endIndex){

5 // We are at the middle, all done!

6 break; // Terminate loop early

7 }else{

8 var temp = firstNames[startIndex]; /* Hold this value while we swap out the \

9 values */

10 firstNames[startIndex] = firstNames[endIndex]; // Swap out the last item wit\

11 h the first item

12 firstNames[endIndex] = temp; // Swap out the first item with the last item

13 startIndex++; // Start iterating the array

14 }

15 }

16 for (var index = 0; index < firstNames.length; index++) {// Iterating over a mut\

17 ated array

18 console.log(firstNames[index]); // The value is looked up based on the value o\

19 f the index

20 }

Results

1 Brandy

2 Kimberly

3 Megan

4 Ferguson

5 Becky

Multiple Arrays

Just like you can have a single array, you can also have multiple arrays. Each of the arrays lives in a different location of memory, allowing you to treat them as two separate entities.

Iterating over two arrays

1 var firstNames = ['Becky', 'Ferguson', 'Megan', 'Kimberly', 'Brandy'];

2 var lastNames = ['Ramirez', 'Miller', 'Anderson', 'Thompson', 'Rodriguez'];

3

4 console.log('First Names:');

5 for (var index = 0; index < firstNames.length; index++) {

6 console.log(firstNames[index]);

7 }

8

9 console.log('\nLast Names:'); // Add an extra line for formatting

10 for (var index = 0; index < lastNames.length; index++) {

11 console.log(lastNames[index]);

12 }

Results

1 First Names:

2 Becky

3 Ferguson

4 Megan

5 Kimberly

6 Brandy

7

8 Last Names:

9 Ramirez

10 Miller

11 Anderson

12 Thompson

13 Rodriguez

Just as you can iterate a single array you also iterate over multiple arrays. If you want to save time you can utilize the same loop.

Iterating over two arrays in the same loop

1 var firstNames = ['Becky', 'Ferguson', 'Megan', 'Kimberly', 'Brandy'];

2 var lastNames = ['Ramirez', 'Miller', 'Anderson', 'Thompson', 'Rodriguez'];

3

4 if(firstNames.length == lastNames.length){ // Safe check to make sure arrays are\

5 the same length

6 // We would not want any undefined values

7 for (var index = 0; index < firstNames.length; index++) {

8 console.log('Full Name:', firstNames[index] + ' ' + lastNames[index]);

9 }

10 }

Results

1 Full Name: Becky Ramirez

2 Full Name: Ferguson Miller

3 Full Name: Megan Anderson

4 Full Name: Kimberly Thompson

5 Full Name: Brandy Rodriguez

Warning

If you are unsure, if you should reuse a loop, just create a new one and optimize your code later. If you try to optimize early in the development life cycle you could end up wasting time in unneeded tasks. Always choose clarity over speed.

The above example can only be valid if both the first names and last names array equal the same length and are sorted in the correct order. If either of these conditions is not true, the program won’t work correctly.

Nested Loops: Arrays can be iterated in a nested loop. This is typically used when, while iterating over one array, you must look up a value in another array.

JavaScript Code Sample

1 var firstNames = ['Becky', 'Ferguson', 'Megan', 'Kimberly', 'Brandy'];

2 var lastNames = ['Ramirez', 'Miller', 'Anderson', 'Thompson', 'Rodriguez'];

3

4 for (var i = 0; i < firstNames.length; i++) {

5 if(i == 0){

6 // No formatting required

7 console.log('First name:', firstNames[i]);

8 }else{

9 console.log('\nFirst name:', firstNames[i]);

10 }

11 // Display all last names

12 for (var j = 0; j < lastNames.length; j++) {

13 console.log('Last Name:', lastNames[j]);

14 }

15 }

Results

1 First name: Becky

2 Last Name: Ramirez

3 Last Name: Miller

4 Last Name: Anderson

5 Last Name: Thompson

6 Last Name: Rodriguez

7

8 First name: Ferguson

9 Last Name: Ramirez

10 Last Name: Miller

11 Last Name: Anderson

12 Last Name: Thompson

13 Last Name: Rodriguez

14

15 First name: Megan

16 Last Name: Ramirez

17 Last Name: Miller

18 Last Name: Anderson

19 Last Name: Thompson

20 Last Name: Rodriguez

21

22 First name: Kimberly

23 Last Name: Ramirez

24 Last Name: Miller

25 Last Name: Anderson

26 Last Name: Thompson

27 Last Name: Rodriguez

28

29 First name: Brandy

30 Last Name: Ramirez

31 Last Name: Miller

32 Last Name: Anderson

33 Last Name: Thompson

34 Last Name: Rodriguez

Pro Tip

Most programmers use i, j, and k to keep track of an index

The loop starts and displays each of the first names with all the lasts names and continues on until it finishes. This might sound like a lot of arrays, but there are true use cases for nesting loops and arrays.

Multidimensional Array

JavaScript does not support two-dimensional arrays. Instead, you store an array inside another array, continuing on with as much memory as is available.

JavaScript Code Sample

1 /* Two dimensional array that's 5 x 5

2 C0 C1 C2 C3 C4

3 R0[1][2][3][4][5]

4 R1[2][4][6][8][10]

5 R2[3][6][9][12][15]

6 R3[4][8][12][16][20]

7 R4[5][10][15][20][25]

8 */

9

10 var row0 = [1,2,3,4,5],

11 row1 = [2,4,6,8,10],

12 row2 = [3,6,9,12,15],

13 row3 = [4,8,12,16,20],

14 row4 = [5,10,15,20,25];

15

16 var table = [row0,row1,row2,row3,row4];

17 console.log(table[0][0]); // Get the first item in the array

Results

1 1

Five arrays are created with the name row* and are added to a new array called table

JavaScript Code Sample

1 var row0 = [1,2,3,4,5],

2 row1 = [2,4,6,8,10],

3 row2 = [3,6,9,12,15],

4 row3 = [4,8,12,16,20],

5 row4 = [5,10,15,20,25];

6

7 var table = [row0,row1,row2,row3,row4];

8

9 for (var row = 0; row < table.length; row++) {

10 var tempRow = [];

11 for (var column = 0; column < table[row].length; column++) {

12 // Displays the row value

13 tempRow[column] = table[row][column];

14 }

15 console.log(tempRow);

16 }

Results

1 [ 1, 2, 3, 4, 5 ]

2 [ 2, 4, 6, 8, 10 ]

3 [ 3, 6, 9, 12, 15 ]

4 [ 4, 8, 12, 16, 20 ]

5 [ 5, 10, 15, 20, 25 ]

We have to use a temporary row to store the current row in order to be able to display it to the console.

Programming Challenge

With the help of the Scientific Method and the use of the Top-Down Design, you will be able to create fairly complex programs. The Top-Down Design is when you break up a large problem into smaller problems. In the previous chapter, we covered the Scientific Method, and I gave you a framework to solve any type of problem that you might encounter both in computing and in science in general. Now, we will be taking a closer look at how to apply the Scientific Method along with a Top-Down Design to solve an actual problem.

1. Understanding the problem

You must fully understand the problem before attempting to solve it. THIS IS IMPORTANT If you fail to understand the problem clearly, you will end up with an invalid solution.

How Exactly Do You Understand the Problem? Just like the Scientific Method, it all starts with a question. The questions that you ask will guide you through the process of understanding the problem. Each of the questions that you ask will get you closer to a valid solution both in design and efficiency.

What Questions Should I Ask? You need to ask enough questions to the point that you feel comfortable with the problem. This can take some time, but be patient and persist.

2. Understand the I/O

As you know by this point, all programs can have input or output. The inputs of a program are the preset variables, values, or assumptions. The output of the program will be the results of a certain process. Understanding what inputs and outputs are is required in order for you to design a valid program.

3. Design from top to bottom

When designing a program, you should begin by sketching out what you’re trying to achieve; typically, a solution to a problem. The sketch should be detailed enough for you to convert it to pseudo code or a detailed flowchart. After you have the detailed design, you can start to work on the expressions that are going to be needed for the program. This would be control structures, loops, and evaluations.

4. Validate your Design

The last step in the design process is to check that the design will solve the problem proposed in Step 1. You can check the program by walking through it step-by-step and evaluating the results. If at any point you find a mistake, fix the issue immediately and continue on with validating your program.

There are different methods for validating a program: automated tests, black box tests, white box tests and many more that are beyond the scope of this book.

Warning

If you decide to look at the solution before attempting to solve the problem yourself, you will NOT learn to program.

I don’t want you to look at the answer and say “Oh that’s easy, anyone can do that.” If you really think anyone can do it, I challenge you to get started with the problem set.

Don’t let the last couple of problems alarm you, they may look highly mathematical but they’re not.

1. Create a program that displays the following message: "Hello World".

· View Solution

2. Create a program that displays the following list of colors: Red, Green, Blue, Cyan, White, Yellow, Magenta

· View Solution

3. Create a program that displays the following colors in reverse: Red, Green, Blue, Cyan, White, Yellow, Magenta

· View Solution

4. Create a program that displays the color with the fewest letters: For example Red, Green, Blue, Cyan, White, Yellow, Magenta would be Red

· View Solution

5. Create a multiplication table that is 20 x 20 and display it on the screen.

· View Solution

6. Create a multiplication table that is 20 x 20 and solve 18 x 13 using the table.

· View Solution

7. Create a program that checks if a string is subset of another string. For example, both car and race are part of racecar.

· View Solution

8. Create the Fizz Buzz game. The game is a simple counting game that increments by one each turn and replaces any number divisible by three using the keyword fizz and any divisible by five with the keyword buzz. If the number is both divisible by three and five, then the output is fizz buzz. Example output: 1,2,fizz,4,buzz,fiz, ... 13,14,fizz buzz, 16

Fizz Buzz

· View Solution

9. Create a program that finds the factorial of any given number.

Factorial

· View Solution

10. Create a program that will maximize the total change that is owed to a customer by providing them the right number of change in quarters, dimes, nickels, and pennies.

Flow Chart

· View Solution

11. Create a program to display the fibonacci sequence. The Fibonacci sequence is a sequence of numbers that can be determined by simply adding the previous two numbers of the sequence together to generate the next number. Example: The fibonacci sequence 1,1,2,3,5,8,13,21,34.

Fibonacci Sequence

· View Solution

12. Create a program that finds the average of a set of numbers. Take for example 12, 13, 18, 2, 32.

Average

· View Solution

13. Calculate the value of e, the mathematical constant.

Sum of e

· View Solution

14. Calculate the value of pi, the mathematical constant.

Sum of pie

· View Solution