Introduction to JavaScript

Introduction to JavaScript

Learning Objectives

This lesson provides an overview of the basic and fundamental topics of JavaScript.

By the end of this lesson, learners will be able to:

  • Use JavaScript data types.

  • Write JavaScript comments.

  • Differentiate between var, let, and const.

  • Use JavaScript operators.

  • Implement JavaScript loops.

  • Iterate through elements using JavaScript.

Table of Contents

  • Section One: Basic JavaScript

  • Introduction to JavaScript

JavaScript Capabilities JavaScript Restrictions

Data Types in JavaScript

$>\quad$ Variables in JavaScript

■ var

  • let

  • const

  • Benefits of let and const

  • Comments in JavaScript

console.log() and Tags

  • JavaScript Operators

  • Arithmetic

  • Comparison

  • Logical

  • String Concatenation Section Two: Control Statements and Loops

  • Control Statements

■ if...else

  • switch

Loops while()

  • for()

  • do...while()

Looping through Strings

User Input

  • String Properties

  • Identifying Numbers

  • Nested Statements

Section 1

Basic JavaScript

Introduction to JavaScript

JavaScript is a high-level and weakly typed scripting programming language. Modern JavaScript is a "safe" programming language, because it does not provide low-level access to memory or CPU; it was initially created for browsers, which do not require that level of access.

JavaScript Facts:

JavaScript was initially created to make web pages more dynamic.

JavaScript programs are called scripts. They can be written right in the HTML, and execute automatically as the page loads or in response to events. Scripts are provided and executed as plain text, and they do not need a special preparation or a compilation to run, as JavaScript is an interpreted language. The JavaScript interpreter (embedded in the browser) is responsible for translating JavaScript code for the browser.

  • It is important to note that JavaScript has almost nothing to do with the programming language named Java. The similar name was inspired by marketing considerations when JavaScript was introduced.

JavaScript Capabilities

JavaScript's capabilities greatly depend on the environment that runs JavaScript. For instance, Node.JS supports functions that allow JavaScript to read and write arbitrary files, perform network requests, etc.

In-browser JavaScript can do everything related to web page manipulation and interaction with the user and the web server. For example, in-browser JavaScript is able to:

  • Add new HTML to the page, change the existing content, and modify styles.

  • React to user actions, and run code on mouse clicks, pointer movements, and key presses.

  • Send requests over the network to remote servers, and download and upload files.

  • Get and set cookies, ask questions to the user, and show messages.

  • Remember data on the client-side (via "local storage").

JavaScript Restrictions

JavaScript's abilities in the browser are limited for the sake of the user's safety. The aim is to prevent a malicious web page from accessing private information or harming the user's data.

Examples of such restrictions include:

JavaScript on a webpage may not read/write or copy arbitrary files on the hard disk, or execute programs. It has no direct access to operating system functions.

Modern browsers allow JavaScript to work with files, but the access is limited and only provided if the user performs certain actions, such as "dropping" a file into a browser window or selecting it via an 〈input> tag.

  • There are ways to interact with the camera, microphone, and other devices, but they require a user's explicit permission. A JavaScript-enabled page may not sneakily enable a web-camera, observe the surroundings, and send the information to some mysterious entity, for instance.

JavaScript Restrictions (continued)

  • Different tabs and browser windows are generally unaware of each other. However, there are times when they can be aware of each other (e.g., when one window uses JavaScript opens the other one). In such cases, JavaScript from one page may not access the other if they come from different sites (e.g., different domain, protocol, or port). This is called the "Same Origin Policy." To work around that, both pages must contain JavaScript code that handles data exchange between them:

The limitation is again for user safety. A page from http://anysite.com, which a user has opened must not be able to access another browser tab with the URL http://gmail.com and steal information from there.

JavaScript can easily communicate over the internet to the server where the current page came from, but its ability to receive data from other sites or domains is constrained. Though it is possible, it requires explicit agreement (expressed in HTTP headers) from the remote side.

Data Types in JavaScript

JavaScript is a loosely typed (high-level, weakly typed, or dynamic type) language, which means that we do not need to specify data types of variables because JavaScript automatically determines the variables' data type.

Some of the available data types in JavaScript include:

  • Number - JavaScript has two different types of numbers.

Integers: Whole numbers such as 1, 100, 5, 100000.

Float: Numbers with decimal values such as 1.5, 34.33, 5.0.

  • String - A sequence of characters, including spaces, enclosed in double quotes, single quotes, or a grave accent

"Hello to String."

'Bye to double quotes.'

Boolean - Logical type values. Boolean can only hold two different values: true or false:

  • Null - Does not belong to any type described above. Its purpose is to indicate that there is no value. Null is an empty or non-existent value, and must be assigned.

  • Undefined - Indicates that a variable has not been assigned a value or null. Variables are often declared without a value. The value could be something that has yet to be calculated or something that will be provided later, like user input.

  • Objects - Used to store collections of data of any of the types mentioned above, or more complex entities.

Variables in JavaScript

A variable is a symbolic name for a memory location. The variable's name can be used to access the data the variable contains. They are called variables because the data can change.

In order to declare a variable, you can use three keywords:

  • var myVariable = "Some value";

  • let mysecond = true;

  • const $\mathrm{PI}=3.141592653589793$;

These declarations operate in similar ways, with a few exceptions, which will be discussed later. The semicolon at the end of the line tells JavaScript that this is the end of the statement. It is important to always include a semicolon to keep in line with best practices.

General rules for variables include:

Name your variables something meaningful and descriptive.

Start your variable names with letters or underscores, never with numbers or special characters.

Variables can contain numbers in the middle or at the end, but not the beginning.

Variables with multiple words in their name should be written in camelCase or snake_case.

The var Statement

The var statement declares a variable in JavaScript that abides by the following rules:

  • It is function-scoped or globally scoped.

  • It is not subject to the temporal dead zone.

  • It creates a global property on the window with the same name.

  • It is reassignable.

  • It is re-declarable.

  • It is subject to hoisting.

You should not use var to declare variables. The use of var predates the latest JavaScript revisions, which added let and const. You should make use of let and const in all cases when coding. Future slides will explain the benefits of doing so in detail.

The let Statement

The let statement declares a variable in JavaScript that abides by the following rules:

  • It is block scoped.

  • It is reassignable.

  • It is not re-declarable within its scope.

It is subject to hoisting.

As an example, consider the following code:

The const Statement

The const statement declares a variable in JavaScript that abides by the following rules:

  • It is block scoped.

  • It is not re-assignable.

It is not re-declarable within its scope.

It is subject to hoisting.

As an example, consider the following code:

const PI $=3.141592653589793$

$P I=3.14 ; / /$ This will give an error.

Benefits of let and const

๑ Since let and const are block-scoped, they allow for cleaner code with fewer errors, especially when working with large files or complex logic.

  • As an example, consider the following code:

If our counters were declared using let, there would be no confusion, and you would not need to spend time looking through your code for the extra counter declaration that was causing errors. This allows you to reuse common variable names throughout the code.

Comments in JavaScript

Comments help document code and increase organization and readability, which is especially helpful when multiple programmers are working on the same content.

Comments in JavaScript can be written with two forward slashes //, which are referred to as line comments, as they end at the physical line end.

// This is a single line comment.

Comments can also start with $/ $ and end with $$ and can span as many lines as needed, which are referred to as block comments.

/* This is a block comment.

It spans multiple Lines. */

Comments are ignored by the interpreter in JavaScript, which means that they will not affect the code in any way. It is important to use comments liberally, as well-documented code, which is easier to scale and maintain.

  • The console object provides access to the browser's debugging console, and can be accessed from any global object.

$>\underline{\log ()}$ is a method of the console object, which allows for any value type to be displayed in the browser's console or in the server-side console. This is an important method for testing and debugging purposes, which we will make use of later.

  • The tag allows you to embed JavaScript into an HTML page. It can have attributes such as "type" and "src."

The "type" attribute allows you to specify the type of text you will be writing in between the opening and closing tag.

The "src" attribute allows you to link a JavaScript file external to your HTML file.

〈script> Tags - Example

There are two ways to include scripts via the 〈script> tag: 1) create a script within the 〈script> tags, and 2) include an external file as thesrc attribute. Examples of each are shown below:

Internal script:

External script:

〈script src="folder/MyJavaScriptFile.js"〉</script〉

JavaScript Operators

The table below shows some common JavaScript operators and their functions, which we will go over in more detail on the following slides.

CategoryOperatorDescriptionExampleResul

Arithmetic

+

Addition

$3+2$

5

-

Subtraction

$3-2$

1

*

Multiplication

$3 * 2$

6

/

Division

$10 / 5$

2

$%$

Modulus

$10 % 5$

9

++

Increment

$x=3 ; x++;$

$x=4$

- -

Decrement

$x=3 ; x--;$

$x=2$

Comparison

$==$

Equal

$5==9$

false

$!=$

Not Equal

$6 !=4$

true

$<$

Less Than

$5<10$

true

$<=$

Less Than or Equal

$3<=3$

true

-

Greater Than

$5>2$

false

$>=$

Greater Than or Equal

$6>=4$

true

Logical

&&

Logical “and”

$3>2 & & 5>3$

true

11

Logical “or”

$3<1|| 5\rangle 2$

true

$!$

Logical "not"

$3 !=5$

true

String

+

String Concatenation

"A" + "BC"

"ABC"

JavaScript Operators: Arithmetic

Most arithmetic operations in coding can be done using the traditional operators of mathematics.

Programming logic adds a few additional operators for efficient coding.

The simple arithmetic operators include:

  • The + operator, which returns the addition of two values.

e.g. $3+4$ returns 7

  • The - operator, which returns the difference between two values.

e.g. 3 - 2 returns 1

  • The * operator, which returns the product of two values.

e.g. $6 * 4$ returns 24

  • The / operator, which returns the division of two values.

e.g. 16 / 8 returns 3

  • The % operator, which returns the remainder of two values.

e.g. $14 % 3$ returns 2

JavaScript Operators: Arithmetic Shortcuts

The basic arithmetic operators also have some useful shortcuts to increase coding efficiency.

For example, if we were to write the following block of code to increment the value of newNumber:

We could instead use the $+=$ operator to increment newNumber, as follows:

let newNumber $=9$;

newNumber $+=1$;

This syntax achieves the same result. You can choose any value to increment by when using this form. The same syntax applies for the other arithmetic operators:

JavaScript Operators: Arithmetic Shortcuts (continued)

The previous $+=$ and $-=$ shortcuts can be further simplified for single-value increments and decrements by using ++ and -, as follows.

The ++ operator increments number values by one, such as:

let newNumber $=9$;

newNumber++; // newNumber is now equal to 10

The - - operator decrements number values by one, such as:

let newNumber $=9$;

newNumber--; // newNumber is now equal to 8

However, if we implement the following code, currentNumber gets set to 9 . We will discuss this behavior on the following slide.

let newNumber $=9$;

let currentNumber $=$ newNumber++;

JavaScript Operators: Arithmetic Shortcuts (continued)

The ++ and -- operators can be placed before or after the variable they are affecting, which produces slightly different results.

When you write let currentNumber $=$ newNumber++; the newNumber variable will first return its current number, which is 9 , and then increment its value. The result of this is that currentNumber is 9 and newNumber is 10.

However, when you write let currentNumber = ++newNumber; the newNumber will increment first, and then return its value. The result of this is that currentNumber and newNumber are both 10.

The same syntax applies for the - - operator. Note that $/ /, * *$, and $% %$ are not operators in JavaScript.

JavaScript Operators: Comparison

Comparison operators are used to determine the relationship between certain values, and will return either true or false, depending on the result of their comparison.

  • The > operator will check if a value is strictly greater than another value.

e.g. $3>4$ returns false

  • The < operator will check if a value is strictly less than another value.

e.g. $5<10$ returns true

  • The $>=$ operator will check if a value is greater than or equal to another value.

e.g. $78>=90$ returns false

  • The $<=$ operator will check if a value is less than or equal to another value.

e.g. $56<=44$ returns false

  • The $==$ operator will check if a value is only equal to another value.

e.g. $10==10$ returns true

  • The $!=$ operator will check if a value is not equal to another value.

e.g. $10 !=30$ returns true

JavaScript Operators: Comparison (continued)

The == operator has some unexpected behaviors. Notice that the following expressions all evaluate to true, even though 3 is an integer and " 3 "' is a string.

So, how can a string be equal to a number?

JavaScript has two types of equal comparison:

$>==$ compares two values, but if they are of different data types it attempts to convert them to the same data type.

e.g. $3==3$ is true, " 3 " $==3$ is true, and $\theta==$ false is also true.

$>===$ (triple equals) compares two values but does not attempt type conversion. This means that not only must the values be equal, but also their data types must also be equal.

e.g. $3===3$ is true, but " 3 "' $===3$ is false.

JavaScript Operators: Logical

Logical operators only work with three types of values: true, false, and null. They are typically used to evaluate the results of comparison operators, which return these values. Combining logical operators allows you to evaluate more complex conditions.

The \&\& (logical AND) operator compares two or more conditions' results and returns true when all conditions are true.

The II (logical OR) operator compares two or more conditions' results and returns true when at least one is true.

The ! (logical NOT) operator negates a given result.

let thisLogic $=!(3>2 & & 6==6) ; / /$ thisLogic is false let thisLogic $=!(3>2|| 6==7) ; / /$ thisLogic is false

Activity: Logical Operators

Make a mental note of what you think each expression below should evaluate to, and then have your program output the result via console. $\log ()$.

For example, I think (10 - $5>=5 % 2)$ \&\& $!(12 * 3<=100 / 3)$ will result in false, so I write:

 console. log((105>=5%2)&&!(123<=100/5))\text { console. } \log ((10-5>=5 \% 2) \& \& !(12 * 3<=100 / 5)) \text {; }

Which outputs... true? I should revisit my logic and figure out where I went wrong! Try the following expressions:

JavaScript Operators: String Concatenation

Concatenation is when two or more things are joined together.

In JavaScript, the plus sign (+) operator is the only arithmetic operator that can be applied to a string. When either operand in an expression is a string, the plus sign will implement string concatenation.

Some examples of string concatenation include:

Knowledge Check

  • Is JavaScript both a high-level and weakly typed programming language?

  • Can you access the memory or CPU with JavaScript?

  • What are two JavaScript data types?

  • What are the two preferred ways to declare variables in JavaScript?

  • What is the difference between var and let?

  • How do you make a comment in JavaScript?

  • How do you output to the console in JavaScript?

  • What are three arithmetic operators in JavaScript, and what do they do?

  • What is the difference between $==$ and $===$ ?

  • What does the logical operator ! accomplish?

  • When you add a plus sign to a string, what will be the result? e.g. console.log $(" 1 "+" 2 ")$;

Section 2

Control Statements and Loops

Control Statements: if...else

if...else statements allow a program to make certain decisions based on inputs and conditions. Depending on the decision the program makes, some code will get executed and another code might be skipped. It is important to know that if statements only evaluate true or false values, but do not produce those results. Notice that the condition is using comparison operators, and they are producing the true or false value that the if statement will evaluate.

The syntax for an if... else statement is as follows:

The open and closed curly brackets denote the body of the if statement. If the condition inside the parentheses is true, the body of the if statement will be executed. If the condition inside the parentheses is false, the body is skipped, and the next portion of code, in this case the else statement, is evaluated. We will go over the else statement further in the upcoming slides.

Control Statements: if... else (continued)

In this example, we have two if statements without else clauses. Since both statements are started with the keyword if, there are two completely separate if statements, which means that after the first if statement is executed, the second if statement will be executed regardless of the outcome of the of the first if statement.

Since both of the conditions evaluate to true, the bodies of each if statement will be executed, and the two messages will be printed to the console.

Control Statements: if... else (continued)

if statements allow for certain decisions to be made based on certain conditions. When those conditions are not met, we can use else statements. The else statement will get executed if the conditions in the if statements are false. It is important to know what the else statement implies based on the conditions given in the if statements. For example:

If it is assumed that the value of number is unknown, the only information given about Number after this example program executes is:

number is greater than or equal to $\mathbf{5}$; or

number is less than 5.

Notice that when number is equal to $\mathbf{5}$, we do not know that information specifically. We can fix this with nested if statements, also known as else if statements, which we will discuss next.

Control Statements: if... else (continued)

Another form of if statement is the else if statement, which are regular if statements linked to each other in sequence. Expanding upon our previous example:

The first if statement tells us if the number is greater than five, the second statement notes whether it is less than five, and the else captures the remaining option - it is equal to five.

Notice that only one statement will execute (never two or all at the same time).

Also notice that there are cases where this logic breaks, which we need to account for. For example, what happens when number is set to a string value, like " $A$ "? In the code above, the output would tell us that " $A$ is equal to 5 ," which is not true.

Control Statements: if... else (continued)

We can address the 'number = "a"' issue by including another layer to our control logic:

It is important to account for all possibilities when using else, or you may run into unintended results within your program.

Control Statements: switch

The switch statement evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case, as well as statements in any case that follows the matching case.

For example:

A breakdown of the syntax for a switch statement is as follows:

The switch keyword signifies the start of a switch statement. A value needs to be provided between the parentheses, and this value can be in the form of a literal or variables.

The case clause specifies what value the switch argument can be. Both the switch argument and its case values must match in data type.

The break keyword tells JavaScript to get out of the switch statement and not evaluate any other case. Without the break keyword, JavaScript will continue to execute other case clauses.

The default keyword is like the else statement. Best practice is to always use the default keyword for case values that are invalid.

Control Statements: switch (continued)

This example simulates a simple calculator that can only perform four different arithmetic operations on two numbers.

Notice that default is being used for the invalid case. Also, the break keyword is not needed in the default case; it depends on the style of the programmer to place the break keyword there.

Loops

A loop is a statement that is used to execute one or more statements repeatedly until a goal is reached. Sometimes, these statements will not be executed at all if that is the way to reach the goal.

We will describe the details of three types of loops in the following slides:

  • while( $)$ - This loop runs a set of instructions until a condition is false.

  • for () - This loop runs a set of instructions for a fixed amount of time.

  • do...while() - This loop is similar to the while() loop, but it will execute a set of instructions at least once before checking its condition.

Loops: while( )

The while statement takes a condition, which can be evaluating a variable or a literal value of any type. It will execute the set of instructions inside its body until the condition evaluates to false.

Just like if statements, a while loop requires a condition inside the parenthesis.

The curly brackets are the body of the while loop and contain the set of instructions to execute during the loop. It is important to note that inside the body of the while loop, there must be something that progresses on each iteration (loop) towards making the condition false to avoid undesirable infinite loops.

Activity - Loops: while( )

Consider this investment problem:

Starting with $$ 10,000$, how many years will it take to double that initial balance to reach $$ 20,000$ at $5 %$ interest?

The algorithm we will use:

  • Start with a year value of $\theta$ and a balance of $$ 10,000$.

  • Repeat the following steps while the balance is less than $$ 20,000$ :

Add 1 to the year value.

Compute the interest by multiplying the balance value by 0.05 (5% interest). This rate will be declared as a const.

  • Add the interest to the balance.

Report the final year value as the answer.

Activity - Loops: while( )

The solution to the activity is as follows, as illustrated by the logic flowchart.

console.log("The investment doubled after " + year + "years.");

Loops: while() - Examples

For the following examples, assume that the variables are already declared and $\mathbf{i}$ is initialized to $\mathbf{5}$.

Output: 54321

When i reaches $\theta$ via the i- - statement, the loop condition becomes false and the loop ends.

The $\mathbf{i}++$ statement causes an "infinite loop" by preventing $\mathbf{i}$ from ever reaching a value less than 0 .

Output: No output.

The statement $\mathbf{i}>\mathbf{5}$ is false and the loop is never executed.

Loops: for( )

Often, you will need to execute a sequence of statements a given number of times. You can use a while loop to do similar tasks, but some use cases work better with a for loop.

The for keyword initiates the loop, and then is followed by parentheses. Arguments in the parentheses are separated by a semicolon. Notice that there is no semicolon after the last statement.

  • The initial value specifies from what value the for loop should start, and this argument is only executed once. Here, a variable can be declared and initialized. Depending on the use of "var" or "let," the variable would have a different scope (scope is discussed later).

  • The condition is what allows the for loop to continue iterating. It is checked before executing the body in each iteration.

  • The last argument will make the condition fail at some point. It is executed after the body in each iteration.

Finally, the body of the loop is enclosed in the curly brackets.

Loops: for () - Examples

Output: 012345

When i reaches 6 via the $\mathbf{i}++$ statement, the loop condition becomes false and the loop ends.

Output: 543210

When $\mathbf{i}$ reaches -1 via the $\mathbf{i}$ - - statement, the loop condition becomes false and the loop ends.

Output: $0246810121416182022242628303234 \ldots$

Since $\mathbf{i}$ is never equal to 9 via the $\mathbf{i}+=2$ statement, this creates an infinite loop. Note that you can use any statement for modifying your initial value, such as $+=,-=, *=, /=, %=$, or more complex expressions.

Activity - Loops: for ()

Consider the following for loop:

  • How many times do the first, second, and third argument get executed?

  • What is the last value of the index at the point of failure?

  • What is the last printed value of index?

The answers to these questions change if the condition of the for loop is changed to index $<10$;

Loops: do...while( )

The while loop's condition is tested as the first thing that occurs in its execution. If that condition returns false, the loop is never executed.

The do... while loop (or do loop) has its condition tested only after at least one execution of the statements. The test is at the bottom of the loop.

This means that the do loop should be used only when the statements must be executed once before there is any knowledge of the condition.

Loops: do...while( ) - Example

In this example, notice that the condition starts with being false, but because the body of the do... while loop is executed before the condition, it is executed at least one time.

Loops: do... while() - Flowcharts

These flowcharts show the difference between a while loop (left) and a do... while loop (right).

Activity - Loops: do... while()

What is the output of the following script?

Answer: 246810

Activity: Loops

Write scripts that achieve the following via loops:

  1. Print all even numbers from 0 to 100.

  2. Print all odd numbers from 0 to 100 .

  3. Given a number, determine if the number is prime, and print "Yes" or "No."

  4. Print all numbers divisible by 4 and 6 for all numbers between 10 and 1,000 (inclusive).

Activity: Looping through Strings

Let's create a program that would ask the user for an arithmetic expression. This program would separate all operators and all numbers. There are already classes that do this type of work, but it is helpful to know how to implement your own version.

For this activity, we will make the following assumptions about the user's input:

  • Any character that is not a number or whitespace is an operator.

  • There are no letters within the string, only numbers and operators.

For example, given the expression $23+3-3 * 5$, our output could be:

  • Numbers: $23,3,3$,

  • Operators:,,$+- *$,

We will walk through the steps of creating this program together in the next few slides, introducing some of the key functions you need to accomplish this task.

Activity: Looping through Strings - User Input

We can ask for user input via the prompt function, which accepts a string as an argument, and will display that string to the user when asking for input. The prompt function returns a string value with the user's input.

With JavaScript, it is not common to take input from the user using the console. However, for the purpose of the following activity, we will use the console to take input.

The first section of our program should look like the code to the right. This script will ask a user for an arithmetic expression, and then output that input to the console.

In future slides, we will forgo the content outside of the tags in our example, assuming that it is structured properly.

Activity: Looping through Strings - String Properties

The input returned by prompt() is of the string data type. In JavaScript, almost every variable is an object. An object is a variable that can model an entity, which means that it has properties made available by JavaScript for the developer to use.

One of the properties of a string is length. For example:

  • let thisstring $=$ "JavaScript"

  • thisstring. length is 10

Note that strings can contain spaces, and spaces are counted as characters when determining length.

We can use this information to create a for loop that iterates through the length of a string, as seen to the right.

Activity: Looping through Strings - String Properties

If we need to see every character in the string, why use $\mathbf{i}$ < userInput.length (which means that if the string is "JavaScript," variable $\mathbf{i}$ will stop at 9)? Shouldn't we use $\mathbf{i}$ « userInput. length, so that $i$ ends at 10 , which is the length of the string?

We start at $\mathbf{i}=\boldsymbol{\theta}$ and end at $\mathbf{i}=9$ because strings are indexed starting at $\boldsymbol{\theta}$. You can access individual characters in a string by using square brackets, as follows:

  • let thisString = "JavaScript"

  • thisString.length is 10

  • thisstring[0] is " $\mathrm{C}$ "

  • thisString[9] is " $\mathrm{t}$ "

We can use this information to expand upon our for loop, adding a variable that accesses the current character of userInput in the loop.

Activity: Looping through Strings - Identifying Numbers

Identifying numbers within a string is relatively simple, thanks to JavaScripts native comparison operators. Every character within a string is treated as a number by the computer system, as described within the American Standard Code for Information Interchange (ASCII).

We can use this information to check for numbers within the userlnput string.

We need to check for anything with an ASCII value greater than or equal to ' $O$ ' AND less than or equal to ' 9 ', which encompasses all of the available digits, as follows:

We enclose this condition in an if... else statement, and will use the body of the if... else statement to add numbers and operators to our final output.

Activity: Looping through Strings - Identifying Numbers

Now, we will create three different variables:

numbers, our string of numbers, operators, our string of operators, and SEPARATOR, our separator value.

We can then use these variables to store the numbers and operators identified within our if... else statement, as seen to the right.

Adding two console. $\log ()$ functions to the end of the script allows us to output the results of our loop.

Finished? Not quite...

Activity: Looping through Strings - Nested Statements

There are a couple problems with this implementation that we need to fix. Run your code using $43+56^{\wedge} 8 * 6$ as your input.

Note the following issues:

Spaces are currently being added to the operators string via our else statement.

Multi-digit numbers are being separated into their individual digits.

The first issue is simple to fix: we add a nested if statement that accounts for spaces, and skips them by doing nothing with them.

The second issue requires a nested while loop that checks for digits following digits. We will add

Activity: Looping through Strings - Nested Statements

Problem: Spaces are currently being added to the operators string via our else statement.

Solution: Add a nested if statement that accounts for spaces, and skips them by doing nothing with them.

Activity: Looping through Strings - Nested Statements

Problem: Multi-digit numbers are being separated into their individual digits.

Solution: Add a nested while loop that checks for digits following digits.

Note that this solution requires a bit of finesse. We need to re-check our string position and current character within the while loop, while also keeping track of the value of $\mathbf{i}$.

We do this by incrementing i within our while loop, and then decrementing it once when the loop is finished so that we do not skip a value when the for loop increments it again at the ends of its loop.

Finished! Test your code with different inputs.

Activity: Looping through Strings - Other Optimizations

Think about other ways you could optimize this script if given the time to do so:

Could you reduce the number of loops?

  • Could you remove the trailing separator from the output string?

  • Could you account for errors in the input, like letters, additional whitespace, and non-operator characters?

Could you convert the input to a valid expression, evaluate it, and return the result?

Come back to this exercise when you have time, and experiment!

PA: Introduction to JavaScript, and Printing Shapes

Please follow the links below to the practice assignments for Introduction to JavaScript and Printing Shapes.

  • PA - 308.1.1 - Introduction to JavaScript

  • PA - 308.1.2 - Printing Shapes

  • You can also find these assignments on Canvas under the Assignments section.

  • If you have technical questions while performing the activities, ask your instructors for assistance.

Knowledge Check

What is an if... else statement used for?

What is the purpose of nesting or linking if... else statements (else if)?

  • What is the difference between a switch statement and an if statement?

What is the keyword used to stop a switch from executing additional case statements?

What is the difference between a for loop and a while loop?

  • How do you avoid infinite loops?

  • What kind of loop will be executed once before there is any knowledge of the condition?

  • What do a for loop, while loop, and do... while loop have in common?

How do you ask for user input using JavaScript?

What is the syntax for accessing a specific character in a string?

Summary

  • JavaScript is a high-level and weakly typed scripting language that does not provide low-level access to memory or the CPU.

JavaScript was created to make web pages more dynamic, and scripts can be written directly inside of the HTML of pages.

  • JavaScript has three different variable declarations: var, let, and const. You should avoid using var, as its scoping can cause issues.

Comments in JavaScript are important for documentation, organization, and readability.

  • You can use console. $\log ($ ) to print to the browser's console for various purposes. JavaScript has many useful built-in operators and shortcuts for operations.

You can use if... else and switch statements to control what blocks of code run in certain situations.

Loops, including for, while, and do... while, can be used to iterate through objects like strings or other data types, as well as to execute a block of code a fixed number of times or until a goal is completed.

You can ask a user for input via the prompt() function, but generally should use HTML forms.

  • Strings have a length property that can be accessed via dot notation, and each character in a string can be accessed with its index via square bracket notation.

Questions?

Last updated