Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
331 views

PROGRAMMING WITH JavaScript Introduction

This document contains an introduction to programming fundamentals in Java script. It covers topics such as computer hardware, algorithms, HTML basics, JavaScript basics, variables and arithmetic, selection, logic, and repetition. The chapters introduce concepts like data types, control structures, operators, loops, and conditional statements that are essential for computer programming.

Uploaded by

Carlos
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
331 views

PROGRAMMING WITH JavaScript Introduction

This document contains an introduction to programming fundamentals in Java script. It covers topics such as computer hardware, algorithms, HTML basics, JavaScript basics, variables and arithmetic, selection, logic, and repetition. The chapters introduce concepts like data types, control structures, operators, loops, and conditional statements that are essential for computer programming.

Uploaded by

Carlos
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 166

CIT 160

INTRODUCTION TO
PROGRAMMING

PROGRAMING FUNDAMENTALS IN JAVA


SCRIPT
Contents
1 CHAPTER 1. COMPUTER HARDWARE........................................................................5
1.1 SEMICONDUCTORS.............................................................................................5
1.2 PARTS OF A COMPUTER......................................................................................6
1.3 DATA SIZES..........................................................................................................7
1.4 CLOCK SPEEDS.....................................................................................................7
1.5 CLASSES OF COMPUTERS....................................................................................7
1.6 CATEGORIES OF SOFTWARE...............................................................................8
1.7 CHARACTER DATA...............................................................................................8
1.8 EXECUTION EXAMPLE.........................................................................................8
2 CHAPTER 2 ALGORITHMS AND PROGRAMS............................................................10
2.1 DEFINING TABLE...............................................................................................10
2.2 ALGORITHMS....................................................................................................10
2.3 COMPUTER PROGRAMS...................................................................................11
2.4 CONTROL STRUCTURES....................................................................................11
2.5 COMPUTER OPERATIONS.................................................................................11
3 CHAPTER 3. HTML basics.........................................................................................13
3.1 STARTING WITH HTML. –..................................................................................13
3.2 DOCUMENT TYPE DECLARATION......................................................................13
3.3 COMMENTS......................................................................................................14
3.4 HTML ELEMENTS...............................................................................................14
3.5 CASE INSENSITIVE.............................................................................................14
3.6 WELL FORMED HTML........................................................................................15
3.7 REQUIRED ELEMENTS.......................................................................................15
3.8 EXAMPLE HTML DOCUMENT............................................................................16
3.9 EXAMPLE HTML DOCUMENT WITH A FORM....................................................16
3.10 FORGETTING TO SAVE AN HTML FILE WITH A SUFFIX OF .html...................16
4 Chapter 4 JavaScript Basics.....................................................................................18
4.1 STARTING WITH JAVASCRIPT............................................................................18
4.2 COMMENTS......................................................................................................20
4.3 STATEMENTS.....................................................................................................20
4.4 RUNNING A PROGRAM.....................................................................................21
4.5 CASE SENSITIVE.................................................................................................21
4.6 DECLARING VARIABLES.....................................................................................21
4.7 STRING CONCATENATION.................................................................................21
4.8 POPUP WINDOWS............................................................................................21
4.9 TEXT FIELDS AND DIVISIONS.............................................................................22
4.10 RESERVED WORDS........................................................................................24
Example..................................................................................................................28
5 CHAPTER 5 VARIABLES AND ARITHMETIC...............................................................55
5.1 DECLARING A VARIABLE....................................................................................55
5.2 VARIABLE TYPES................................................................................................55
5.3 ASSIGNING TO A VARIABLE...............................................................................56
5.4 DECLARING A CONSTANT.................................................................................56
5.5 DESK CHECKS....................................................................................................57
5.6 SWAPPING VALUES...........................................................................................57
5.7 ARITHMETIC EXPRESSIONS...............................................................................57
5.8 ARITHMETIC OPERATORS.................................................................................57
5.9 MODULUS.........................................................................................................57
5.10 OPERATOR PRECEDENCE...............................................................................58
5.11 CELCIUS TO FAHRENHEIT..............................................................................58
5.12 CELSIUS TO FAHRENHEIT...............................................................................59
5.13 ASSIGMENT OPERATORS...............................................................................59
5.14 INCREMENT AND DECREMENT OPERATORS.................................................60
5.15 OPERATOR PRECEDENCE REVISITED.............................................................61
5.16 MATH OBJECT...............................................................................................61
5.17 VOLUME OF A CYLINDER...............................................................................62
5.18 ROUND TO DECIMAL PLACES........................................................................62
6 CHAPTER SELECTION...............................................................................................77
6.1 RELATIONAL OPERATORS.................................................................................77
6.2 EVEN INTEGERS.................................................................................................80
6.3 ODD INTEGERS..................................................................................................80
6.4 QUADRATIC FORMULA.....................................................................................80
7 CHAPTER 7 LOGIC....................................................................................................82
7.1 Logical operator................................................................................................82
7.2 Choosing a group..............................................................................................83
7.3 Disneyland autopia...........................................................................................86
7.4 Exclusive Or.......................................................................................................87
7.5 Finding a range.................................................................................................87
7.6 Logical equivalences.........................................................................................88
7.7 Using the Morgan’s Law...................................................................................88
7.8 Advanced word Search.....................................................................................89
7.9 Truth tables.......................................................................................................89
7.10 Common mistakes.........................................................................................91
8 REPETITION..............................................................................................................97
8.1 Pre-test and Post-test Loops.............................................................................97
8.2 Counting and Sentinel Controlled Loops..........................................................97
8.3 Repetition control structures...........................................................................98
8.4 Simple counting loop........................................................................................99
8.5 Zero-Based Counting Loop..............................................................................100
8.6 Skipping loop..................................................................................................100
8.7 Infinite loop.....................................................................................................100
8.8 Compound interest.........................................................................................101
8.9 Break...............................................................................................................102
8.10 Prime numbers............................................................................................102
8.11 Repetitive strings........................................................................................103
9 CHAPTER 9. FUNCTIONS........................................................................................111
9.1 Advantages of functions.................................................................................111
9.2 Writing a function...........................................................................................111
9.3 Calling a function............................................................................................113
9.4 Variable scope.................................................................................................115
9.5 Pseudo random Integer..................................................................................122
9.6 Code Reuse.....................................................................................................122
9.7 Area of a triangle............................................................................................123
9.8 Surface Area of a pyramid..............................................................................124
9.9 How long to invest..........................................................................................126
9.10 Greatest common divisor............................................................................127
10 CHAPTER 10. ARRAYS............................................................................................133
10.1 Declaring an array.......................................................................................133
10.2 Creating an Array........................................................................................134
10.3 Array length.................................................................................................135
10.4 Accessing an element..................................................................................135
10.5 Filling an Array.............................................................................................135
10.6 Filling an array with a Ramp........................................................................136
10.7 Reversing an Array......................................................................................136
10.8 Summing the values in an Array.................................................................137
10.9 Finding a value (linear search)....................................................................137
10.10 Parallel Arrays.............................................................................................138
10.11 Finding a Range...........................................................................................139
10.12 Finding a Value (Binary Search)..................................................................142
10.13 Array methods.............................................................................................143
1 CHAPTER 1. COMPUTER HARDWARE
1.1 SEMICONDUCTORS
What is a semiconductor?
It is a small component the conduct or sometime conduct electricity

What type of semiconductors there are?


There are many kinds of them and each has a different function:
Conductor Function and description
Capacitor Stores electricity
Diode Allows electricity to flow in only one
direction
LED (light emitting diode) It emits light when current flows through
it
Resistor It resists to current flow and protects
other components of surges in electricity
Transistor It has two inputs and one output. A
larger current that flows through the
outer wires can be controlled by a small
current that flows through the center
wire.

What is a computer chip?


It is an integrated circuit composed of many semiconductors.

1.2 PARTS OF A COMPUTER

What are parts of a computer?

HARDWARE PARTS
Power supply It converts electricity from 150 volts, 60
Hz AC current to 3.3 volts DC current in
order to do electricity useful for
computer
Keyboard
Motherboard The main circuit to which other
components are attached.
Bus They are wires and integrated circuits
that are used to carry information from
one component to other within
motherboard
Bios Basic input and output system. It is a
flash memory that contains information
that CPU executes when computer is
turned on.
CPU Central processing unit. it is a large and
expensive integrated circuit in which the
majority of calculation are done within
the computer
Cache Located on the CPU. It temporally stores
data and instructions. It stores data
from main memory in order to provide
CPU information fast. Its contents are
erased when computer is turned off.
Main memory It stores data and instructions for CPU.
Memory is volatile and is erased when
computer is turned off. It is known also
as random-access memory (RAM)
Hard drive It stores data semi permanently even
when computer is turned off
CD or DVD drive
Jump, thumb, or flash drive It stores data semi permanently.
Information can be added and erased
electrically.
Monitor

1.3 DATA SIZES


¿What are some examples of data size that a computer can process?

A bit Abbreviation for binary


digit
Nibble Four bit together to form 1111
a binary number.
byte Eights bits joined to form
a binary number
kylobyte 210 1,024
Megabyte 220 1,048,576
Gigabyte 230 1,073,744,1824
terabyte 240 1.099511628 x1012
Petabyte 250 1.125899907x1015
exabyte 260 1.152921505x1018

1.4 CLOCK SPEEDS


What is a clock?
A clock within a CPU is an electrical circuit that repeatedly produces an electrical signal
that pulses, its voltage rises and falls like the picture bellow:

What is the relation between the electrical signal pulses produced by the clock and a
core?
Core is designed to complete one instruction at the end of each pulse.

What is the measurement unit for a clock speed?


The hertz which is one cycle per second

What are some terms to measure clock speeds?

Hertz A unit of frequency equal to one cycle


per second
Kilohertz One thousand cycles per second
megahertz One million cycles per second
Gigahertz One billion cycles per second

What does it mean that a computer has a clock speed of 2.5 gigahertz?
It means that a single core is designed to complete 2.5 billion of instructions per
second.
1.5 CLASSES OF COMPUTERS
According what are computers classified?
According to size and primary purpose.

Micro or personal computers Laptop computer, smartphones


workstation For use of a person designed to
accomplish engineering and scientific
tasks.
Mainframe Many people can use it at the same time.

1.6 CATEGORIES OF SOFTWARE


What is a computer software?
It is a list of instructions that hardware executes.

Software classification according to its PURPOSE


Aplication It is a computer software created to
complete an specific task like writing
documents, solving mathematics,
drawing, playing.
Examples: Word, Excel, Photoshop, ect.
Operating system It is a computer software that manages
hardware. It prevents application to
interacts with hardware but in allows
interact indirectly.
Example: Microsoft windows, linux,
MacOs

1.7 CHARACTER DATA


How are things (pictures, songs, text, instrucions) stored in a computer’s memory?
It is stored in numbers.
What programmers invented to assign numbers to characters and symbols?
They invented coding systems

What are the most expanding coding systems currently?


They are two:
ASCII (American Standard Code for information interchange). it assings a number to
each English letter and common punctuation symbol.
Unicode. It is a larger coding system that includes ASCII.

1.8 EXECUTION EXAMPLE

Review questions
Which of the following does a computer use primarily to store data? (mark all that
apply)
a. power supply
b. keyboard
c. motherboard
d. bus
e. central processing unit (CPU)
f. cache
g. main memory
h. hard drive
i. digital versatile disc (DVD)
j. thumb drive or jump drive
k. monitor
2. Match each of the following types of computer memory with the physical quantity
that each manipulates to store data.
Cache Light
Main Magnetization
memory
Flash Electric
memory charge
Hard drive
DVD drive

3. Computer memory that is volatile have electricity in order to store data. Which of
the following memories are volatile?
Cache Volatile
Main memory Volatile
Flash memory
Hard drive
DVD

4. Match each term to its corresponding size in bytes.


5. Assume the average movie uses 3 gigabytes of space on a hard drive. Which of these
is the smallest size that can be store 200 average size movies?
a. 500 megabytes
b. 500 gigabytes
c. 1 terabyte
d. 1 petabyte
6. Consider a quad core CPU with a clock speed of 2.8 gigahertz. In theory, how many
instructions per second is it able to complete?
a. 2.8 million
b. 2.8 billion
c. 11.2 billion
d. 20 billion
7. Which character coding system includes Englisth letters? (Mark all that apply)
a. ASCII
b. Unicode
8. If you wanted to type a letter in Hebrew, which character coding system would your
computer need to use to store your letter?
a. ASCII
b. Unicode
2 CHAPTER 2 ALGORITHMS AND
PROGRAMS
2.1 DEFINING TABLE

What is an algorithm?
It is a list of steps to perform a task.

What is a defining table and what are its sections?


It is a useful tool to help one better understand a problem and its sections are:
 input
 processing
 output
What is the defining table purpose and why is important?
Its purpose is to help people better understand a problem and it is important because
the better a problem is understood the better the algorithm to solve it will be.
Input Processing Ouput

2.2 ALGORITHMS

An algorithm to brush teeth


Hold your toothbrush and take a piece of toothpaste.
Carry toothpaste over your teeth with tooth brush.
Brush every side of your teeth.
Vertical inside and outside sides have to be brush with an up and down movement of
your toothbrush, at least 15 times per length your toothbrush can cover.
The horizontal side of your teeth has to be brush with an in out movement.

2.3 COMPUTER PROGRAMS


What a computer program is composed of?
It is composed of data and instructions.

How instructions are found in a computer program?


They are found as steps in algorithms. In JavaScript they are called statements.

2.4 CONTROL STRUCTURES


What a control structure does?
It controls the order in which the computer executes a statement in a program.

How many control structures are there and what are they?

Control structure Description


Sequence It causes the computer to execute
statements from top to bottom.
Selection It causes the computer to execute just a
group of selected statements.
Repetition It causes the computer repeats a group
of statements.
Function call and return It causes the computer to execute
statements in another function and to
return a result from the other function to
the call point.
Try, catch, and throw It is used to communicate that errors
have ocurred

2.5 COMPUTER OPERATIONS


What are the seven basic operation a computer can perform?
They are:
1. Receive data
2. Write out data
3. Assign a value to a variable or memory location
4. Perform arithmetic
5. Compare values
6. Repeat a group of actions
7. Call a function and return from that function.
Input Processing Ouput
Area of lawn Multiply by 0.01 Season cost
Multiply by 15

Input Processing Ouput


Number of regular hours Multiply regular hours by Net pay
Overtime hours regular hourly wage to get
regular hourly wage regular pay
regular hours
Multiply overtime hours
by regular hourly day by
1.5 to get overtime pay.

Add regular pay and


overtime pay to get gross
pay

Multiply gross pay by 0,15


to get tax

Substract tax from gross


pay to get net pay
Get regular hours, overtime hours, and regular hourly wage from the user
Multiply regular hours by regular hourly wage to get regular pay
Multiply overtime hours by regular hourly day by 1.5 to get overtime pay.
Add regular pay and overtime pay to get gross pay
Multiply gross pay by 0,15 to get tax
Substract tax from gross pay to get net pay
Display net pay for the user to see.
3 CHAPTER 3. HTML basics
What is HTML?
Hypertext markup language, is a computer language useful to write documents for the
world wide web of information on internet.

3.1 STARTING WITH HTML. –


What is necessary to start writing HTML documents?

A text editor like Visual studio Code VS Code, brackets Brackets or sublime
Sublime and a browser

What is the suffix that has to be written in every HTML document?


.html

3.2 DOCUMENT TYPE DECLARATION

How must HTML 5 document have to begin?


With a document type declaration <!DOCTYPE HTML>

What is it going to happen if DTD is not written at the top of the document?
Browser could take it as older version of HTML and fail when reading code.
3.3 COMMENTS
What is a comment?
It is a text or note that is not executed as code but it is just instructions or something
like that for another web programmer to read. It is written always inside this symbols:
<!--comment-->

3.4 HTML ELEMENTS


What is?
It is just a part of an HTML document

What an element is composed of?


It is composed of an opening tag, optional text, and a closing tag.

What does an opening tag contain?


It contains a tag name and optional attributes.

What an attribute is composed of?


It is composed of a name and a value, surrounded by straight quote marks, separated
by an equal sign.
Element

Attr. name

Attr. value

<div class=''note'' id= ''high''>At high altitude bake at 50 higher</div>

Attribute closing tag


text
Tag name

<input type=''text'' id=''futureValue'' size=''5'' />

3.5 CASE INSENSITIVE


What does it mean that HTML is not case sensitive?
It means that it doesn’t matter your code is written in uppercase o lowercase letters,
code will be read as well.

What is the standard convention?


The standard convention is to write HTML elements in lowercase it is easier to read
than uppercase because these last have the same size and cannot be differenced
immediately.
The convention is to write tag and attribute in lowercase except for the DOCTYPE
declaration.

What are the reasons web developers use lower case letters?
 Lowercase it is easier to read than uppercase because these last have the same
size and cannot be differenced immediately.
 If a conversion of an HTML 5 document has to be changed to XHTML
document, which requires lowercase attributes and tag, the change will be
easier.

3.6 WELL FORMED HTML

What means that an HTML document should be well formed?


It means that the document is written properly and it will be executed without any
problem.
It means this:
The document includes just standard tags and attributes.
Opening tags have their closing tag, except void tags.
Nested tags are ended before the enclosing tag end.
How are named tags that do not have a closing tag?
They are named void tags and some of them are: <meta>, <br>, <input>.

How can I ensure an HTML document is well formed?


By uploading to the one validator at http://validator.w3.org/

3.7 REQUIRED ELEMENTS

How every HTML5 must start?


It has to start with Document type declaration.
<!DOCTYPE HTML> and an open tag <html>

What are the two sections an HTML5 document must have?


They are head and body section.

What should the head section have?


It should have a meta tag <meta>, that states the document character, and a title tag
<title>

How every HTML5 skeleton should look similar?


<!DOCTYPE HTML>
<html lang=''en-us''>
<head>
<meta charset=''utf-8''>
<title>Title</title>
</head>
<body>
</body>
</html>
3.8 EXAMPLE HTML DOCUMENT

3.9 EXAMPLE HTML DOCUMENT WITH A FORM

How does a programmer add functionality to an HTML document?


By writing JavaScript code between opening and closing <script> tags.

What does an id attribute do within an HTML document and how must they be?
It identifies an element in a HTML document, and it must be unique in a document.
There is and id attribute with a value high in the next element

Element

Attr. name

Attr. value

<div class=''note'' id= ''high''>At high altitude bake at 50 higher</div>

Attribute closing tag


text
Tag name
What does an onclick attribute do?
It tells the browser what to do when a user clicks on a button.

3.10 FORGETTING TO SAVE AN HTML FILE WITH A SUFFIX OF


.html
What is the suffix an HTML document has to end whit in order to be recognized for a
browser?
.html

REVIEW QUESTIONS

Write the HTML 5 document type declaration as it should appear at the top of all
HTML 5 documents. Include the surrounding less than (<) and greater than (>) symbols
in your answer.
<!DOCTYPE HTML>
What is the firs tag in an HTML 5 document? Include the surrounding less than (<) and
greater than (>) symbols in your answer.
<html lang= ''en-us''>
</html>

What are the two main sections that every HTML 5 document must have?
They are head and body sections

Inside which of the two main sections does the <title> tag belong?
It belongs to the head section.

What is the tag to begin the largest type of heading? Include the surrounding less than
(<) and greater than (>) symbols in your answer.
<h1> </h1>

What is the tag to begin a paragraph? Include the surrounding less than (<) and greater
than (>) symbols in your answer.
<p> </p>

Write the HTML tag and its attributes for creating a text field. Include the surrounding
less than (<) and greater than (>) symbols in your answer.
<textarea id=''txaMessage'' rows='''' cols=''''> </textarea>

Write the HTML tag and its attributes for creating a button. Include the surrounding
less than (<) and greater than (>) symbols in your answer.
<button type= ''button'' onclick=''sendText()''>Send</button>

What is the attribute that a programmer can use to uniquely identify each element
within an HTML document?
This is the id attribute.
What are the characters that begin an HTML comment?
<!-- a comment here -->
What is the tag that ends HTML document? Include the surrounding less than (<) and
greater than (>) symbols in your answer.
</hmtl>

ASSIGMENTS
1. Create and validate a well-formed HTML 5 documents that tells a short version of
your life story. The document must include at least one heading and two paragraphs.
<!DOCTYPE HTML>
<html lang=''en-us''>
<head>
<meta charset=''utf-8''>
<title>My life story</title>
</head>
<body>
<h1>My life story</h1>
<p>
</p>
<p>
</p>

</body>
</html>

2. Create and validate a well-formed HTML 5 documents that advertises a business


that you own or would like to start. The document must include at least one heading
and two paragraphs.
<!DOCTYPE HTML>
<html lang=''en-us''>
<head>
<meta charset=''utf-8''>
<title>Business advertisement</title>
</head>
<body>
<h1> Business advertisement </h1>
<p></p>
<p></p>
</body>
</html>
3. Create and validate a well-formed HTML 5 documents that contains two text
fields, a button, and a div. The text fields and the div must each have a unique id
attribute.

<!DOCTYPE HTML>
<html lang=''en-us''>
<head>
<meta charset=''utf-8''>
<title></title>
</head>
<body>
<h1></h1>
<p>
</p>
</body>
</html>

https://www.w3schools.com/

Week 4

4 Chapter 4 JavaScript Basics


4.1 STARTING WITH JAVASCRIPT
Where should JavaScript code be written?
It should be written in the head part of the document.

What is the purpose to write the comment “use strict” at the top of the Java code?
The purpose is to indicate to the browser to use a set o stricter rules to find some
possible mistakes in JavaScript code.
<DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>My first JavaScript Program</title>

<script>
"use strict";
/* Defining Table
* Input: No user input
* Processing: None
*/
function showMessage(){
//The next line of code causes the computer to open a popup window that
contains the words "Water is delicious!"
alert("Water is delicious");
}
</script>
</head>
<body>
<button type="button" onclick="showMessage()">Message
</button>
</body>
</html>
In the previous html document, what is the element that create the message button?

<button type="button" onclick="showMessage()">Message </button>

What does the onclick attribute causes when a user clicks the button?

It causes the computer to execute the JavaScript code contained in the onclick
attribute, it executes the showMessage function.

Where does the showMessage fuction begin and end?

function showMessage(){

//The next line of code causes the computer to open a popup window that

contains the words "Water is delicious!"

alert("Water is delicious")

What command causes the computer to open a popup window that contains the text
“Water is delicious”?
It is the alert command

4.2 COMMENTS
What is a comment in JavaScript program?
It is just a phrase that contains information for the programmer or other who will read
the document, it is not executed as a part of the program.

What are the two styles of comments in JavaScript and how do they begin and end?
Single line comment Multiline comment
Begins Ends Begins ends
// At the end of the /* */

line of text
Example Example
//The next line of code causes /* Defining Table
the computer to open a popup window * Input: No user input

that contains the words "Water is * Processing: None

delicious!" */

4.3 STATEMENTS
What is a statement and how does it end?

A complete command within a program and it ends with a semicolon, example:

function showMessage(){

//The next line of code causes the computer to open a popup window that

contains the words "Water is delicious!"

alert("Water is delicious");

How do programmers group statements in a block?

It is done by surrounding the statements with curly braces {and}

4.4 RUNNING A PROGRAM


4.5 CASE SENSITIVE
What must you type to cause the computer to open a popup window?

I must type alert not Alert

4.6 DECLARING VARIABLES


What is a variable?

It is a location within the computer’s memory to store data.

How we declare variable in JavaScript?

By writing the keyword let and the variable’s name. Exs.:

let price;

let numStudents;

let name;
4.7 STRING CONCATENATION
What is a string of text and how must they be surrounded?
It is a piece of text. And it must be surrounded with quotes.

What can I do with string concatenation operator and what is its symbol?

You can create a large string of text from smaller strings of text. And its symbol is (+)

Example>
let name= “Samantha”;
let message= “Hello, ” + name + “. How are you today?”;
4.8 POPUP WINDOWS
What is the program to get a user input by opening a popup window where a user
can type input?
Example 2.

<DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>A program to say hello</title>
<script>
/* Defining Table
* Input: A person's name
* Processing: Create a greeting for that person
* Output: The greeting
*/
function greetUser(){
//This line prompts the user to type in his name.
let name = prompt("Please enter your name");
// Create a personalized greeting for the user.
let greeting = "Hello" +name+". I hope you are well today.";
// The next line causes the computer to display a greeting to the user in a
popup window.
alert(greeting);
}
</script>
</head>
<body>
<button type="button" onclick="greetUser()">Hello
</button>
</body>
</html>

In the undergoing example what are the elements or codes that causes things that
are in the next first column?
Actions Response
Causes the computer to open a popup let name = prompt("Please enter your

window, which prompts the user to name");

enter her name


After the user enter her name, causes let greeting = "Hello" +name+". I hope

the computer to create a personalized you are well today.";

greeting for the user.


Causes the computer to display the alert(greeting);

greeting in another popup window

4.9 TEXT FIELDS AND DIVISIONS


Write a program that uses a text field for input and a div for ouput.

<DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Applied scripture</title>
<script>
/* Defining Table
* Input: A person's name
* Processing: Create a verse of scripture for that person
* Output: The scripture
*/
function applyScripture(){
//Get the user's name from the text field that has the id of "nameInputBox"
and store it in a variable named name.
let name = document.getElementById('nameInputBox').value;
// Use a string concatenation to create a verse of scripture personalized for
the user.
let scripture = "I," +name+", having bee born of" + "goodly parents,
therefore I was taught somewhat" + "in all the learning of my father.";
// Display the scripture in the div that has id "outputDiv".
document.getElementById('outputDiv').innerHTML = scripture;
}
</script>
</head>
<body>
Please enter your name: <input type= "text" id="nameInputBox">
<button type="button" onclick="applyScripture()">Verse</button>
<div id="outputDiv"></div>
</body>
</html>
What has to be done to get input from a text field?

Inside a HTML document a text field has to be written as shown above:


Please enter your name: <input type= "text" id="nameInputBox">
Attribute value can be different.

What is the built-in JavaScript function to get the input from a user´s input from a
text field and how it is used?
It is the document.getElementById built-in function and is written as shown in the
ongoing line:
let name = document.getElementById('nameInputBox').value;
It has to be inside a function in JavaScript.

What are the codes to send output to a div?

Add a div with a unique attribute in the HTML document as shown above:

<div id="outputDiv"></div>

Add code to your function that uses the div´s id and innerHTML attributes to store the
results from the function in the div as shown above:
document.getElementById('outputDiv').innerHTML = scripture;
It has to be inside a function in JavaScript.
Scripture is the name of the string that will be the ouput for the div.

What do the rules of HTML require?

Each attribute value must be unique within a document.


An id attribute cannot be empty or contains spaces:
<iput type=”text” id= “salesInput”>
<div id=”output”></div>

4.10 RESERVED WORDS


None of these words should be use as variables or function names in JavaScript
programs
JavaScript Keywords
break case catch const
continue debugger default delete
do else false finally
for function if in
instanceof let new null
of return switch this
throw true try typeof
undefined var while with

JavaScript Types
Array Boolean Date Function
Math Number Object RegExp
String

JavaScript Objects
document event window

JavaScript Unused but Reserved Words


abstract boolean byte char
class double enum export
extends final float goto
implements import int interface
long native package private
protected public short static
super synchronized throws transient
void volatile yield

Review questions

1. What is the HTML tag that begins a section of JavaScript code? Include the

surrounding less than (<) and greater than (>) symbols in your answer.

2. What is the JavaScript keyword to declare a variable?

3. What does the document.getElementById function do?

a. display a message in a pop-up window and get input from a user

b. find an element within an HTML document

c. convert a number to text

d. convert to a number

4. What is the symbol that causes the computer to perform string concatenation?

5. Write the HTML tag that makes a text field that can be used by this JavaScript

statement:
let addr = document.getElementById(´address´). value;

Include the surrounding less than (<) and greater than (>) symbols and

necessary attributes in your answer.

6. Write the opening HTML tag to put a button in an HTML document. Include

the surrounding less than (<) and greater than (>) symbols and necessary

attributes in your answer.

7. What is the attribute of a button that contains JavaScript code that will be

executed when a user clicks on that button?

8. Write the opening HTML tag that makes a div that can be used by this

JavaScript statement:

document.getElementById(´output´). innerHTML = hearRate;

Include the surrounding less than (<) and greater than (>) symbols and necessary

attributes in your answer.

JACASRIPT W3SCHOOL

Why Study JavaScript?

JavaScript is one of the 3 languages all web developers must learn:

   1. HTML to define the content of web pages

   2. CSS to specify the layout of web pages

   3. JavaScript to program the behavior of web pages

INTRODUCTION

JavaScript Can Change HTML Content

One of many JavaScript HTML methods is getElementById().


The example below "finds" an HTML element (with id="demo"), and changes the

element content (innerHTML) to "Hello JavaScript":

document.getElementById("demo").innerHTML = "Hello JavaScript";

<!DOCTYPE html>
<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p id="demo">JavaScript can change HTML content.</p>

<button type="button" onclick='document.getElementById("demo").innerHTML =


"Hello JavaScript!"'>Click Me!</button>

</body>
</html>

JavaScript Can Change HTML Attribute Values

In this example JavaScript changes the value of the src (source) attribute of

an <img> tag:

<!DOCTYPE html>
<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p>JavaScript can change HTML attribute values.</p>

<p>In this case JavaScript changes the value of the src (source) attribute of an
image.</p>

<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on
the light</button>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">

<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off


the light</button>

</body>
</html>

JavaScript Can Change HTML Styles (CSS)

Changing the style of an HTML element, is a variant of changing an HTML attribute:

Example

document.getElementById("demo").style.fontSize = "35px";

<!DOCTYPE html>
<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p id="demo">JavaScript can change the style of an HTML element.</p>

<button type="button"
onclick="document.getElementById('demo').style.fontSize='35px'">Click Me!</button>

</body>
</html>

JavaScript Can Hide HTML Elements

Hiding HTML elements can be done by changing the display style:

Example
document.getElementById("demo").style.display = "none";

<!DOCTYPE html>
<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p id="demo">JavaScript can hide HTML elements.</p>

<button type="button" onclick="document.getElementById('demo').style.display='none'">Click Me!</button>

</body>
</html>

JavaScript Can Show HTML Elements


Showing hidden HTML elements can also be done by changing the display style:

Example

document.getElementById("demo").style.display = "block"

<!DOCTYPE html>
<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p>JavaScript can show hidden HTML elements.</p>

<p id="demo" style="display:none">Hello JavaScript!</p>

<button type="button"
onclick="document.getElementById('demo').style.display='block'">Click Me!</button>

</body>
</html>

JAVASCRIPT WHERE TO

The <script> Tag

In HTML, JavaScript code is inserted between <script> and </script> tags.

Example

<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript in Body</h2>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
</body>
</html>

JavaScript Functions and Events


A JavaScript function is a block of JavaScript code, that can be executed when "called"
for.
For example, a function can be called when an event occurs, like when the user clicks a
button.

JavaScript in <head> or <body>


You can place any number of scripts in an HTML document.
Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in
both.

JavaScript in <head>
In this example, a JavaScript function is placed in the <head> section of an HTML page.
The function is invoked (called) when a button is clicked:
Example
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
  document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>

When the customer clicks the button the paragraph content changes.

JavaScript in <body>
In this example, a JavaScript function is placed in the <body> section of an HTML page.
The function is invoked (called) when a button is clicked:
Example
<!DOCTYPE html>
<html>
<body>

<h1>A Web Page</h1>


<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>

<script>
function myFunction() {
  document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>

</body>
</html>

When the customer clicks the button the paragraph content changes.

External JavaScript
Scripts can also be placed in external files:
External file: myScript.js
function myFunction() {
  document.getElementById("demo").innerHTML = "Paragraph changed.";
}
External scripts are practical when the same code is used in many different web pages.
JavaScript files have the file extension .js.
To use an external script, put the name of the script file in the src (source) attribute of
a <script> tag:
Example
<script src="myScript.js"></script>

You can place an external script reference in <head> or <body> as you like.


The script will behave as if it was located exactly where the <script> tag is located.
External scripts cannot contain <script> tags.

External JavaScript Advantages


Placing scripts in external files has some advantages:
 It separates HTML and code
 It makes HTML and JavaScript easier to read and maintain
 Cached JavaScript files can speed up page loads
To add several script files to one page  - use several script tags:
Example
<script src="myScript1.js"></script>
<script src="myScript2.js"></script>

External References
External scripts can be referenced with a full URL or with a path relative to the current
web page.
This example uses a full URL to link to a script:
Example
<script src="https://www.w3schools.com/js/myScript1.js"></script>
Example
<script src="/js/myScript1.js"></script>

<script src="myScript1.js"></script>

JAVASCRIPT OUTPUT

JavaScript Display Possibilities


JavaScript can "display" data in different ways:
 Writing into an HTML element, using innerHTML.
 Writing into the HTML output using document.write().
 Writing into an alert box, using window.alert().
 Writing into the browser console, using console.log().

Using innerHTML
To access an HTML element, JavaScript can use
the document.getElementById(id) method.
The id attribute defines the HTML element. The innerHTML property defines the HTML
content:
Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My First Paragraph</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>

</body>
</html>

Using document.write()
For testing purposes, it is convenient to use document.write():
Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
document.write(5 + 6);
</script>

</body>
</html>

<!DOCTYPE html>
<html>
<body>

<h2>My First Web Page</h2>


<p>My first paragraph.</p>

<p>Never call document.write after the document has finished loading.


It will overwrite the whole document.</p>

<script>
document.write(5 + 6);
</script>

</body>
</html>

Using document.write() after an HTML document is loaded, will delete all existing


HTML:

Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<button type="button" onclick="document.write(5 + 6)">Try it</button>

</body>
</html>
The document.write() method should only be used for testing.

Using window.alert()
You can use an alert box to display data:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<script>
window.alert(5 + 6);
</script>

</body>
</html>

You can skip the window keyword.


In JavaScript, the window object is the global scope object, that means that variables,
properties, and methods by default belong to the window object. This also means that
specifying the window keyword is optional:
Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
alert(5 + 6);
</script>

</body>
</html>

Using console.log()
For debugging purposes, you can call the console.log() method in the browser to
display data.
You will learn more about debugging in a later chapter.
Example
<!DOCTYPE html>
<html>
<body>

<script>
console.log(5 + 6);
</script>

</body>
</html>

JavaScript Print
JavaScript does not have any print object or print methods.
You cannot access output devices from JavaScript.
The only exception is that you can call the window.print() method in the browser to
print the content of the current window.
Example
<!DOCTYPE html>
<html>
<body>

<button onclick="window.print()">Print this page</button>

</body>
</html>

JAVASCRIPT STATEMENTS

Example
var x, y, z;    // Statement 1
x = 5;          // Statement 2
y = 6;          // Statement 3
z = x + y;      // Statement 4

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Statements</h2>

<p>A <b>JavaScript program</b> is a list of <b>statements</b> to be executed by a


computer.</p>

<p id="demo"></p>

<script>
var x, y, z; // Statement 1
x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement 4

document.getElementById("demo").innerHTML =
"The value of z is " + z + ".";
</script>

</body>
</html>

JavaScript Programs
A computer program is a list of "instructions" to be "executed" by a computer.
In a programming language, these programming instructions are called statements.
A JavaScript program is a list of programming statements.
In HTML, JavaScript programs are executed by the web browser.

JavaScript Statements
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.
This statement tells the browser to write "Hello Dolly." inside an HTML element with
id="demo":
Example
document.getElementById("demo").innerHTML = "Hello Dolly.";

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Statements</h2>

<p>In HTML, JavaScript statements are executed by the browser.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "Hello Dolly.";
</script>

</body>
</html>

Most JavaScript programs contain many JavaScript statements.


The statements are executed, one by one, in the same order as they are written.
JavaScript programs (and JavaScript statements) are often called JavaScript code.

Semicolons ;
Semicolons separate JavaScript statements.
Add a semicolon at the end of each executable statement:
var a, b, c;     // Declare 3 variables
a = 5;           // Assign the value 5 to
b = 6;           // Assign the value 6 to b
c = a + b;       // Assign the sum of a and b to c

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Statements</h2>
<p>JavaScript statements are separated by semicolons.</p>

<p id="demo1"></p>

<script>
var a, b, c;
a = 5;
b = 6;
c = a + b;
document.getElementById("demo1").innerHTML = c;
</script>

</body>
</html>

When separated by semicolons, multiple statements on one line are allowed:


a = 5; b = 6; c = a + b;

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Statements</h2>

<p>Multiple statements on one line is allowed.</p>

<p id="demo1"></p>

<script>
var a, b, c;
a = 5; b = 6; c = a + b;
document.getElementById("demo1").innerHTML = c;
</script>

</body>
</html>

On the web, you might see examples without semicolons. Ending statements with
semicolon is not required, but highly recommended.

JavaScript White Space


JavaScript ignores multiple spaces. You can add white space to your script to make it
more readable.
The following lines are equivalent:
var person = "Hege";
var person="Hege";
A good practice is to put spaces around operators ( = + - * / ):
var x = y + z;

JavaScript Line Length and Line Breaks


For best readability, programmers often like to avoid code lines longer than 80
characters.
If a JavaScript statement does not fit on one line, the best place to break it is after an
operator:
Example
document.getElementById("demo").innerHTML =
"Hello Dolly!";

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Statements</h2>

<p>
The best place to break a code line is after an operator or a comma.
</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
"Hello Dolly!";
</script>

</body>
</html>

JavaScript Code Blocks


JavaScript statements can be grouped together in code blocks, inside curly brackets
{...}.
The purpose of code blocks is to define statements to be executed together.
One place you will find statements grouped together in blocks, is in JavaScript
functions:
Example
function myFunction() {
  document.getElementById("demo1").innerHTML = "Hello Dolly!";
  document.getElementById("demo2").innerHTML = "How are you?";
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Statements</h2>
<p>JavaScript code blocks are written between { and }</p>

<button type="button" onclick="myFunction()">Click Me!</button>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
function myFunction() {
document.getElementById("demo1").innerHTML = "Hello Dolly!";
document.getElementById("demo2").innerHTML = "How are you?";
}
</script>

</body>
</html>

In this tutorial we use 2 spaces of indentation for code blocks.


You will learn more about functions later in this tutorial.

JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript action to be
performed.
Visit our Reserved Words reference to view a full list of JavaScript keywords.

In JavaScript you cannot use these reserved words as variables, labels, or function
names:
abstract arguments await* boolean

break byte case catch

char class* const continue

debugger default delete do

double else enum* eval

export* extends* false final

finally float for function

goto if implements import*

in instanceof int interface

let* long native new


null package private protected

public return short static

super* switch synchronized this

throw throws transient true

try typeof var void

volatile while with yield


Words marked with* are new in ECMAScript 5 and 6.
You can read more about the different JavaScript versions in the chapter JS Versions.

Removed Reserved Words


The following reserved words have been removed from the ECMAScript 5/6 standard:
abstract boolean byte char

double final float goto

int long native short

synchronized throws transient volatile


Do not use these words as variables. ECMAScript 5/6 does not have full support in all
browsers.

JavaScript Objects, Properties, and Methods


You should also avoid using the name of JavaScript built-in objects, properties, and
methods:
Array Date eval function

hasOwnProperty Infinity isFinite isNaN

isPrototypeOf length Math NaN

name Number Object prototype

String toString undefined valueOf

Java Reserved Words


JavaScript is often used together with Java. You should avoid using some Java objects
and properties as JavaScript identifiers:
getClass java JavaArray javaClass

JavaObject JavaPackage
Other Reserved Words
JavaScript can be used as the programming language in many applications.
You should also avoid using the name of HTML and Window objects and properties:
alert all anchor anchors

area assign blur button

checkbox clearInterval clearTimeout clientInformation

close closed confirm constructor

crypto decodeURI decodeURIComponent defaultStatus

document element elements embed

embeds encodeURI encodeURIComponent escape

event fileUpload focus form

forms frame innerHeight innerWidth

layer layers link location

mimeTypes navigate navigator frames

frameRate hidden history image

images offscreenBuffering open opener

option outerHeight outerWidth packages

pageXOffset pageYOffset parent parseFloat

parseInt password pkcs11 plugin

prompt propertyIsEnum radio reset

screenX screenY scroll secure

select self setInterval setTimeout

status submit taint text

textarea top unescape untaint

window

HTML Event Handlers


In addition you should avoid using the name of all HTML event handlers.
Examples:
onblur onclick onerror onfocus

onkeydown onkeypress onkeyup onmouseover

onload onmouseup onmousedown onsubmit

Here is a list of some of the keywords you will learn about in this tutorial:
Keyword Description

break Terminates a switch or a loop

continue Jumps out of a loop and starts at the top

debugger Stops the execution of JavaScript, and calls (if available) the
debugging function

do ... Executes a block of statements, and repeats the block, while a


while condition is true

for Marks a block of statements to be executed, as long as a condition is


true

function Declares a function

if ... else Marks a block of statements to be executed, depending on a


condition

return Exits a function

switch Marks a block of statements to be executed, depending on different


cases

try ... Implements error handling to a block of statements


catch

var Declares a variable


JavaScript keywords are reserved words. Reserved words cannot be used as names for
variables.

JAVASCRIPT SYNTAX

JavaScript syntax is the set of rules, how JavaScript programs are constructed:
var x, y, z;       // Declare Variables
x = 5; y = 6;      // Assign Values
z = x + y;         // Compute Values
JavaScript Values
The JavaScript syntax defines two types of values:
 Fixed values
 Variable values
Fixed values are called Literals.
Variable values are called Variables.

JavaScript Literals
The two most important syntax rules for fixed values are:
1. Numbers are written with or without decimals:
10.50

1001

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>Number can be written with or without decimals.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 10.50;
</script>

</body>
</html>

2. Strings are text, written within double or single quotes:


"John Doe"

'John Doe'

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Strings</h2>

<p>Strings can be written with double or single quotes.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 'John Doe';
</script>

</body>
</html>

JavaScript Variables
In a programming language, variables are used to store data values.
JavaScript uses the var keyword to declare variables.
An equal sign is used to assign values to variables.
In this example, x is defined as a variable. Then, x is assigned (given) the value 6:
var x;

x = 6;

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Variables</h2>

<p>In this example, x is defined as a variable.


Then, x is assigned the value of 6:</p>

<p id="demo"></p>

<script>
var x;
x = 6;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

JavaScript Operators
JavaScript uses arithmetic operators ( + - * / ) to compute values:
(5 + 6) * 10

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Operators</h2>

<p>JavaScript uses arithmetic operators to compute values (just like algebra).</p>


<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = (5 + 6) * 10;
</script>

</body>
</html>

JavaScript uses an assignment operator ( = ) to assign values to variables:


var x, y;
x = 5;
y = 6;

<!DOCTYPE html>
<html>
<body>

<h2>Assigning JavaScript Values</h2>

<p>In JavaScript the = operator is used to assign values to variables.</p>

<p id="demo"></p>

<script>
var x, y;
x = 5;
y = 6;
document.getElementById("demo").innerHTML = x + y;
</script>

</body>
</html>

JavaScript Expressions
An expression is a combination of values, variables, and operators, which computes to
a value.
The computation is called an evaluation.
For example, 5 * 10 evaluates to 50:
5 * 10

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Expressions</h2>
<p>Expressions compute to values.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 5 * 10;
</script>

</body>
</html>

Expressions can also contain variable values:


x * 10

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Expressions</h2>

<p>Expressions compute to values.</p>

<p id="demo"></p>

<script>
var x;
x = 5;
document.getElementById("demo").innerHTML = x * 10;
</script>

</body>
</html>

The values can be of various types, such as numbers and strings.


For example, "John" + " " + "Doe", evaluates to "John Doe":
"John" + " " + "Doe"

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Expressions</h2>

<p>Expressions compute to values.</p>

<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "John" + " " + "Doe";
</script>

</body>
</html>

JavaScript Keywords
JavaScript keywords are used to identify actions to be performed.
The var keyword tells the browser to create variables:
var x, y;
x = 5 + 6;
y = x * 10;

<!DOCTYPE html>
<html>
<body>

<h2>The var Keyword Creates Variables</h2>

<p id="demo"></p>

<script>
var x, y;
x = 5 + 6;
y = x * 10;
document.getElementById("demo").innerHTML = y;
</script>

</body>
</html>

JavaScript Comments
Not all JavaScript statements are "executed".
Code after double slashes // or between /* and */ is treated as a comment.
Comments are ignored, and will not be executed:
var x = 5;   // I will be executed
// var x = 6;   I will NOT be executed

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Comments are NOT Executed</h2>

<p id="demo"></p>
<script>
var x;
x = 5;
// x = 6; I will not be executed
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

JavaScript Identifiers
Identifiers are names.
In JavaScript, identifiers are used to name variables (and keywords, and functions, and
labels).
The rules for legal names are much the same in most programming languages.
In JavaScript, the first character must be a letter, or an underscore (_), or a dollar sign
($).
Subsequent characters may be letters, digits, underscores, or dollar signs.
Numbers are not allowed as the first character.
This way JavaScript can easily distinguish identifiers from numbers.

JavaScript is Case Sensitive


All JavaScript identifiers are case sensitive. 
The variables lastName and lastname, are two different variables:
var lastname, lastName;
lastName = "Doe";
lastname = "Peterson";

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript is Case Sensitive</h2>

<p>Try change lastName to lastname.</p>

<p id="demo"></p>

<script>
var lastname, lastName;
lastName = "Doe";
lastname = "Peterson";
document.getElementById("demo").innerHTML = lastName;
</script>

</body>
</html>
What you have in the browser:
JavaScript is Case Sensitive
Try change lastName to lastname.
Doe

JavaScript does not interpret VAR or Var as the keyword var.

JavaScript and Camel Case


Historically, programmers have used different ways of joining multiple words into one
variable name:
Hyphens:
first-name, last-name, master-card, inter-city.
Hyphens are not allowed in JavaScript. They are reserved for subtractions.
Underscore:
first_name, last_name, master_card, inter_city.
Upper Camel Case (Pascal Case):
FirstName, LastName, MasterCard, InterCity.
Lower Camel Case:
JavaScript programmers tend to use camel case that starts with a lowercase letter:
firstName, lastName, masterCard, interCity.

JavaScript Character Set


JavaScript uses the Unicode character set.
Unicode covers (almost) all the characters, punctuations, and symbols in the world.
JAVASCRIPT COMMENTS

JavaScript comments can be used to explain JavaScript code, and to make it more
readable.
JavaScript comments can also be used to prevent execution, when testing alternative
code.

Single Line Comments


Single line comments start with //.
Any text between // and the end of the line will be ignored by JavaScript (will not be
executed).
This example uses a single-line comment before each code line:
Example
// Change heading
document.getElementById("myH").innerHTML = "My First Page";

// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";

<!DOCTYPE html>
<html>
<body>

<h1 id="myH"></h1>
<p id="myP"></p>

<script>
// Change heading:
document.getElementById("myH").innerHTML = "JavaScript Comments";
// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";
</script>

</body>
</html>

This example uses a single line comment at the end of each line to explain the code:
Example
var x = 5;      // Declare x, give it the value of 5
var y = x + 2;  // Declare y, give it the value of x + 2

Multi-line Comments
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored by JavaScript.
This example uses a multi-line comment (a comment block) to explain the code:
Example
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";

It is most common to use single line comments.


Block comments are often used for formal documentation.

Using Comments to Prevent Execution


Using comments to prevent execution of code is suitable for code testing.
Adding // in front of a code line changes the code lines from an executable line to a
comment.
This example uses // to prevent execution of one of the code lines:
Example
//document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Comments</h2>

<h1 id="myH"></h1>

<p id="myP"></p>

<script>
//document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
</script>

<p>The line starting with // is not executed.</p>

</body>
</html>

This example uses a comment block to prevent execution of multiple lines:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Comments</h2>

<h1 id="myH"></h1>

<p id="myP"></p>

<script>
/*
document.getElementById("myH").innerHTML = "Welcome to my Homepage";
document.getElementById("myP").innerHTML = "This is my first paragraph.";
*/
document.getElementById("myP").innerHTML = "The comment-block is not
executed.";
</script>

</body>
</html>

source: https://www.w3schools.com/js/default.asp

TASK
Write three HTML documents that contain JavaScript code.

1. In a file named greeting.html, type the HTML and JavaScript


code for example 2 from chapter 4 of the textbook in I-Learn.
Modify the code to display any message you want. The modified
message must include the user’s input. Validate the code and
load it in a web browser to run and test it. If it doesn’t run
correctly, fix it until it runs correctly.
2. In a file named scripture.html, type the HTML and JavaScript
code for example 3 from chapter 4 of the textbook in I-Learn.
Modify the code by changing the scripture that is displayed to the
user. Your program may display any scripture you want except 1
Nephi 1:1. The changed scripture must include the user’s input.
Validate the code and load it in a web browser to run and test it. If
it doesn’t run correctly, fix it until it runs correctly.
3. In a file named template.html, write a well formed HTML 5
document that you can use as a template for future assignments.
At a minimum, your template must contain all the tags that are
required in an HTML 5 document as explained in Chapter 3 of the
textbook in the “Required Tags” section. In addition, your
template must contain an opening  script  tag, a closing  script  tag,
at least one  input  tag, an opening  button  tag, a closing  button  tag, an
opening  div  tag, and a closing  div  tag.

Week 5

Order of operations
Parentheses
Exponents
Multiplication/Division
Addition/Subtraction

Variables

<!DOCTYPE HMTL>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title> Variables</title>
</head>
<body>
<script langueage "javascript" type="text/javascript">
//Declare Variables
var userName;
var userBottingAverage;
var ageInDogYears;

// Initiable Variables
userName = "Carlos Medina";
userBattingAverage = .312;
ageInDogYears = 11*7;

//Combined Declaration and Initialization


var computerType= "MAcintosh";

document.write(userName);
document.write ("<br/>");
document.write(userBattingAverage);
document.write ("<br/>");
document.write("Age in dog years:" + ageInDogYears)

</script>
</body>
</html>

document.write(userName); This code causes to write variable


userName in the browser.

document.write ("<br/>"); This cause to generate a break


between to lines in values written in the browser.

<!DOCTYPE HMTL>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title> Variables</title>
</head>
<body>
<script langueage "javascript" type="text/javascript">
//Declare Variables
var atBots;
var walks;
var hits;
var playerName;

playerName = "Carlos ";


atBots=213;
walks = 19;
hits=59;

var battingAverage = 59 / (213-19);


document.write("battingAverage is: " + battingAverage);
document.write("<br/>");
document.write(playerName + atBots);
</script>
</body>
</html>
document.write(playerName + atBots); This code is to join two
variables, one that contents a string and other a number.

5 CHAPTER 5 VARIABLES AND


ARITHMETIC
Inside what is data stored when this is in the computer’s memory?
It is store inside variables.

What does a variable have?


It has a name, type, value and scope.

5.1 DECLARING A VARIABLE

How is a variable declare?


There are two ways. First, using the keyword var followed of the name of the variable
or the keyword let.

How can many variables be declared in a single line?


It can be done by writing names followed by a coma.
var name, name2, name3 ;
let name, name2, name3 ;

What is the difference between var and let?


A variable declared with var keyword has a function scope and one declared with a
let keyword has a block scope.
How must a variable name start and what other things have to be taken in count?
With and upper or lowercase, the underscore (_), or the dollar sign ($). It cannot have
spaces and it can contain number, letters, the underscore, or dollar sign.

5.2 VARIABLE TYPES

What does a variable type indicate to the computer?


It indicates what kind of data can be stored in the variable and what operations the
computer my perform on the variable.
What kind of variable type do we have?

Type Purpose Example


boolean Stores true of false true
number A number with o without 74.3
a decimal point
string A string of text “San Diego”
function A part of a program function () {return 27;}
created using the keyword
function
object An object such as an Array {nane: “Sam”, phone:
or Date “1778”}

5.3 ASSIGNING TO A VARIABLE

What is the assignment operator and what can a programmer do with that?
It is (=). It is for a programmer to assign a value to a variable
name = value;
Example
let price, discRate;
let title;
price = 12.95
discRate =0.25
title = “A poor wayfaring man of grief”

How the computer determines the variable’s type?


By the data stored in the variable.

What is initializing a variable?


It is assigning a value to a variable when it is declared, example:

var name= value, name2= value2, name3= value3;


let price = 12.95;
let title = “A Poor Wayfaring Man of Grief”;

5.4 DECLARING A CONSTANT


How is a constant declared and what is it?
It is a variable that cannot be changed. To declare a constant the keyword const must
be used.

When does the assigning of a value to a constant have to be done?


When this is declared.

Example: const name = value, name2= value2, name3= value3…;


Declare a constant named g and assign the value 9.807 to it. Also, declare a constant
named team and assign the text “Nuggets” to it.
const g= 9.807;
const team = “Nuggets”;

5.5 DESK CHECKS


5.6 SWAPPING VALUES

What is swapping values?


It is a way the program can exchange values between variables.

How can swapping values be done?

By using a temporary variable.

Example:

let swap = a;
a= b;
b=swap;

5.7 ARITHMETIC EXPRESSIONS

5.8 ARITHMETIC OPERATORS

What are the JavaScript operators?

Operator Name Algebraic JavaScript


expression Expression
- Negation -r -r
* Multiplication Vt or v x t v*t
/ Division x/y or x÷y x/y
% modulus r mod s r%s
+ Addition P+q P+q
- Subtraction f-3 f-3
= Assignment s=t s=t

5.9 MODULUS
What does modulus operator return?
The remainder operator returns the signed remainder (+ or -) of a division.

What the remainder sign depends on in JavaScript?


It depends on the dividend (operand on the left the %)

Examples:

7%3= 1
12%3=0
-6%4=-2
6%-4=2
-6%-4-= -2

5.10 OPERATOR PRECEDENCE

What is the JavaScript operator precedence?


Operator(s) Name(s) Precedence
() Parentheses Highest (evaluated first)
- Negation
*/% Multiplication, division,
modulus
+ - Addition, subtraction
= Assignment Lowest (evaluated last)

How does computer evaluate an expression with two or more operators with the same
precedence?

It evaluates them from left to right.

5.11 CELCIUS TO FAHRENHEIT

9
f = c+32
5

What does parseFloat function do and how is it written?


It converts a string to a number.
In the next code a parseFloat is used to convert the variable value of the variable text,
which is a string with text, to a number.

<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Convert Celsius to Fahrenheit</title>

<script>
/* Input: a temperature in Celsius
* Processing: convert the temperature from Celsius
to Fahrenheit
* Output: the temperature converted to Fahrenheit
*/
function celsToFahr() {
// Read a Celsius temperature from the user.
let text =
document.getElementById('celsiusInputBox').value;
// Convert what the user typed from text into a
number.
let c = parseFloat(text);

// Convert the Celsius temperature into


Fahrenheit.
let f = c * 9 / 5 + 32;

// Display the Fahrenheit temperature to the


user.
document.getElementById('fahrenDiv').innerHTML =
f;
}
</script>
</head>

<body>
Enter a temperature in Celsius: <input type="text"
id="celsiusInputBox">
<button type="button"
onclick="celsToFahr()">Convert</button>
<div id="fahrenDiv"></div>
</body>
</html>

What does parseInt function do?


It converts a string of texts to an integer.
parseInt will convert 75.814 to 75.

5.12 CELSIUS TO FAHRENHEIT

5
c= ( f −32)
9

What problem does 5/9 division cause in some programming languages such Java, C++
and C?

Due tue these programs perform integer division truncate the result by simply
dropping the digits after the decimal.

5.13 ASSIGMENT OPERATORS

What are assignment operators and what are them?


They are shortcuts for performing arithmetic using the current value of a variable and
then storing the result of the arithmetic back into that variable.

Operator Name Example Equivalent


example
*= Multiplication x *= 5; x= x*5;
assignment
/= División s /= t; s = s/t;
assignment
%= Modulus w %= z; w = w%z;
assignment
+= Addition x += y; x = x + y;
assignment
-= Subtraction r -= t; r =r – t;
assignment

Examples:

Program to compute sales tax


let subtotal = 175;
let tax = subtotal * 0.06;
let total= subtotal + tax;

let total = 175;


let tax = total * 0.06;
total += tax;

5.14 INCREMENT AND DECREMENT OPERATORS

What are increment and decrement operators and what do they do?
They are more shortcut operators and they add or subtract one to the value of the
variable:

Operator Name Example Equivalent


Examples
++ pre-increment ++x; x +=1; x =x +1;
post-increment x++;
-- pre-decrement --t; t -=; t=t-1;
post-decrement t --;

How does pre and post increment operator work in an arithmetic operation?

Pre increment ++x causes the value of x to increment one first and after to perform the
arithmetic.
Post increments x++ doesn’t affect to arithmetic operation.

What is the purpose of post increment operator knowing that the value increases
after the other calculations in the same statement are done?

The purpose is to prepare the variable to be used later in the program.


When there is no difference between writing any of the two versions of the
increment operator?
When it is in a statement all by itself.

Check the Examples


let a= 4;
let b= ++ a * 3 + 2;

b= 17

let a= 4;
let b= ++ a * 3 + 2;

b= 14

let q=7;
let s= 2 + 18 / --q;

s=5

5.15 OPERATOR PRECEDENCE REVISITED

Operator (s) Name (s) Precedence (s)


() parentheses Highest (evaluated first)
- nagation
++ -- increment, decrement
*/% Multiplication, division,
modulus
+- addition, subtraction
= += += *= /= %= Assignment operators Lowest (evaluated last)

5.16 MATH OBJECT


What is the math object?
It is an object built into JavaScript that enables a program to perform more
advanced mathematical computations.
What are some of the math object constants?

Constant Description Algebraic Approximate value


Expression
E Euler´s number e 2.71828
LN2 Natural logarithm ln 2 0.69315
of 2
LN 10 Natural logarithm ln 10 2.30259
of 10
LOG2E Base-2 logatithm of log2e 1.44270
Euler´s number
LOG10E Base-10 logatithm log10e 0.43429
of Euler´s number
PI Ratio of a circle´s π 3.14159
circumference to
its diameter
SQRT1_2 Square root of 1/2 1 0.70711

SQRT2 Square root of 2



√2
2
1.41421

What are some of the object functions?

Function Description
abs(x) Absolute value of x
acos(x) Arccosine of x in radians
asin(x) Arcsine of x in radians
atan(x) Arctangent of x as a numeric value in the
range [-π/2, π/2] radians
atan2(y, x) Arctangent of the quotient of its
arguments
ceil(x) Smallest integer that is larger than or
equal to x
cos(x) Cosine of an angle x (x in radians)
exp (x) Euler´s number raised to the power of x
(ex)
floor(x) Largest integer that is smaller than of
equal to x
log(x) Natural logarithm of x (ln x)
max (x, y, z) Largest value of many numbers
min (x, y, z) smallest value of many numbers
pow (y, x) y raised to the power of x (yx)
random() A pseude random number in the range
[0.0, 1.0]
round(x) Integer that is nearest x
sin(x) Sine of an angle x (x is in radians)
sqrt(x) Square root of x
tan() Tangent of an angle x (x is in radians)

5.17 VOLUME OF A CYLINDER

5.18 ROUND TO DECIMAL PLACES

How is the fuction named Math.round used?


See the highlighted lines in the next code:

<html lang= "en-us">


<head>
<meta charset="utf-8">
<title>Converting volume from quart to liters</title>
<script>
/* Input: A volume in quarts
* Processing: convert the volume from quarts to liters.
* Output: Volume converted to liters.
*/
function quartolit(){
//Obtaining quarts from user input and changing it from text string to number
let text = document.getElementById('quartinputbox').value;
let vc= parseFloat(text);
//Converting volume from quarts to liters
let vl= vc*0.946353;
//Rounding the volume in liters to two digits
let digits= 2;
let multiplier = Math.pow(10, digits);
vl = Math.round(vl*multiplier)/multiplier
// Displaying the volume in liters to the user
document.getElementById('literdiv').innerHTML = vl;
}
</script>
</head>
<body>
Enter a volume in quarts: <input type="text" id="quartinputbox">
<button type= "button" onclick="quartolit()">Convert</button>
<div id="literdiv"></div>
</body>
</html>

REVIEW QUESTIONS

1. Declare two variable named balance and rate


var balance, rate;

2. Declare a variable named inventor and assign the text “Franklin” to it


3. In JavaScript what do both the keywords var and let do?
a. reserve space in the computer´s memory for a variable
b. store a value in variable
c. convert a number to a text
d. prompt the user for input
4. What does the parseInt function do?
a. use an ID to find an element in a document
b. display a message in a pop-up window
c. convert an integer to text
d. convert text to integer
5. What does the parsFloat function do?
a. use an ID to find an element in a document
b. display a message in a pop-up window
c. convert a number to text
d. convert text to a number
6. After a computer executes the following JavaScript code, variable a will be of
what data type?
let a= false;
7. After a computer executes the following JavaScript code, variable a will be of
what data type? Hint: pay attention to the double quotes.
let a= false;
8. After a computer executes the following JavaScript code, variable c will be of
what data type?
let c= 15;
9. After a computer executes the following JavaScript code, variable e will be of
what data type and hold what value?
let c= 15;
let d= -2.17;
let e= c+d;
10. After a computer executes the following JavaScript code, variable h will be of
what data type and hold what value?
let f= “Her name is”;
let g= “Isabella”;
let h= f+g;
11. After a computer executes the following JavaScript code, variable k will be of
what data type?
let i = document.getElementById(´number1´).value;
let j = document.getElementById(´number2´).value;
let k = I + j;
12. After a computer executes the following JavaScript code, variable p will be of
what data type?
let m = parseInt(document.getElementById(´number1´).value);
let n = parseFloat(document.getElementById(´number2´)).value;
let p = m + n;
13. After a computer executes the following JavaScript code, variable r will be of
what data type?
let c = 15;
let r = “You found” + c + “coins.”;
14. Write a JavaScript statement to calculate the amount of energy released during
a nuclear reaction. In other words, translate E= mc 2 into JavaScript. Assume
that the variables m and c already exist and that each holds a value. When
writing your answer, be sure to declare E and use the variable names given in
the equation above.
15. The semi-perimeter, s, of a triangle with side lengths a, b, and c is given by the
a+ b+c
formula s= Translate this formula into JavaScript, Assume that the
2
variables a, b and c already exist and that each holds a value. When writing
your answer, be sure to declare s and use the variable names given in the
equation above.
6−n
16. Translate this formula r =2 k + into JavaScript. Assume that the variables k,
3 p2
n and p already exist and that each holds a value. When writing your answer,
be sure to declare r and use the variable names given in the equation above.
17. Rewrite the following JavaScript statement so that it doesn´t use the + =
operator but still has the same functionality.
z +¿ x−3∗ y ;

Assume that the variables x, y and z already exist and that each holds a value.
When writing your answer, be sure to use the variables names given in the
statement above.
18. Rewrite the following JavaScript statement so that it doesn´t use the * =
operator but still has the same functionality.
b∗¿ q−s ;

Assume that the variables b, q and s already exist and that each holds a value.
When writing your answer, be sure to use the variables names given in the
statement above. Hint: pay close attention to operator precedence.

PROGRAMMING ASSIGNMENTS

1. Write a defining table and a JavaScript program that asks a user for a
volume in quarts and then converts that value into liters. Your program
should correctly handle real numbers such as 7.54.
2. Write a defining table and a JavaScript program that asks a user for a
distance in kilometers and then converts that value into miles. Your
program should correctly handle real numbers such as 7.54.
3. An employee at a grocery store must frequently place boxes of cans in
stacks. Write a defining table and a program that allows him to enter the
total number of boxes and the number boxes he will place in each stack.
Your program must output the number of stacks except the last one must
have the exact number of boxes that the employee specifies. The last stack
must have the exact number of fewer boxes. For example if the employee
enters 74 total boxes and 6 boxes in each stack your program must output
13.
4. A teacher frequently divides her class into teams. Write a defining table and
program that allows her to enter the number of students in her class and
the number of teams she wants. The number of members on each team
must be as balanced as possible. In other words, if not all of the teams can
have the same number of members then some of the teams will have only
one more member than other teams. Your program must output a phrase
that tells the teacher how to divide her class into teams. For example, if the
teacher entered 22 class members and 5 teams, your program must output
“2 teams with 5 members and 3 teams with 4 members.” Your program
must list the larger teams first.
5. Write a defining table and a JavaScript program to compute the mileage of
a vehicle. Your program should allow the user to enter the beginning and
ending odometer readings and the number of gallons of gasoline used and
should output the mileage in miles per gallon. Your program should
correctly handle real numbers.
6. When you exercise to strengthen your heart, you should maintain your
heart rate within a range. To find that range, subtract your age from 220.
This difference is your maximum heart rare pe minute. Your heart simply
will not beat faster than this maximum (220-age). When exercising to
strength your heart, you should keep your heart rate between 65% and 85%
of your heart´s maximum. Write a defining table and a JavaScript program
that asks a person´s age and computes and output the slowest and fastest
rates necessary to strengthen his heart.
7. Write a defining table and a JavaScript program to compute and output an
employee´s after tax pay. Your program will read from the keyboard the
number of regular hours that an employee worked and that employee´s
wage, and then compute that employee´s after tax pay. Tax is 15% of the
employee´s gross pay. Your program should correctly handle real numbers.
8. The length of a cable can be approximated with this formula:
8 d2
L=s+
3s
where L is the length of the cable, s is the distance that the cable must
span, and d is the distance the cable will sag or dip. Write a defining table
and a program that allows a user to enter the distance a cable must span
and the distance the cable will sag. Your program must compute and output
the length of the cable.

9. The size of a car tire in the United States is represented with three numbers
like this: 205/60R 15. The first number is the width of the tire in millimeters.
The second number is the aspect ratio. The third number is the diameter in
inches of the wheel that the tire fits. Write a defining table and a program
that reads from the keyboard those three numbers for a tire and computes
and outputs the volume of space inside that tire. The volume of space
inside a tire can be approximated with this formula.
π w 2 a (wa+2540 d )
v=
10000000
where v is the volume in cubic centimeters, w is the width of the tire in
millimeters, a is the aspect ratio of the tire, and d is the diameter of the
wheel in inches.
W3scools

JavaScript Operators
❮ PreviousNext ❯

Example
Assign values to variables and add them together:
var x = 5;         // assign the value 5 to x
var y = 2;         // assign the value 2 to y
var z = x + y;     // assign the value 7 to z (5 + 2)
Try it Yourself »
The assignment operator (=) assigns a value to a variable.
Assignment
var x = 10;
Try it Yourself »
The addition operator (+) adds numbers:
Adding
var x = 5;
var y = 2;
var z = x + y;
Try it Yourself »
The multiplication operator (*) multiplies numbers.
Multiplying
var x = 5;
var y = 2;
var z = x * y;
Try it Yourself »

JavaScript Arithmetic Operators


Arithmetic operators are used to perform arithmetic on numbers:
Operator Description

+ Addition

- Subtraction

* Multiplication

** Exponentiation (ES2016)

/ Division

% Modulus (Division Remainder)

++ Increment

-- Decrement
Arithmetic operators are fully described in the JS Arithmetic chapter.

JavaScript Assignment Operators


Assignment operators assign values to JavaScript variables.
Operator Example Same As

= x=y x=y

+= x += y x=x+y

-= x -= y x=x-y

*= x *= y x=x*y

/= x /= y x=x/y

%= x %= y x=x%y

**= x **= y x = x ** y
The addition assignment operator (+=) adds a value to a variable.
Assignment
var x = 10;
x += 5;
Try it Yourself »
Assignment operators are fully described in the JS Assignment chapter.

JavaScript String Operators


The + operator can also be used to add (concatenate) strings.
Example
var txt1 = "John";
var txt2 = "Doe";
var txt3 = txt1 + " " + txt2;
The result of txt3 will be:
John Doe
Try it Yourself »
The += assignment operator can also be used to add (concatenate) strings:
Example
var txt1 = "What a very ";
txt1 += "nice day";
The result of txt1 will be:
What a very nice day
Try it Yourself »
When used on strings, the + operator is called the concatenation operator.

Adding Strings and Numbers


Adding two numbers, will return the sum, but adding a number and a string will return
a string:
Example
var x = 5 + 5;
var y = "5" + 5;
var z = "Hello" + 5;

The result of x, y, and z will be:


10
55
Hello5
Try it Yourself »
If you add a number and a string, the result will be a string!

JavaScript Comparison Operators


Operator Description

== equal to

=== equal value and equal type

!= not equal

!== not equal value or not equal type

> greater than

< less than

>= greater than or equal to

<= less than or equal to


? ternary operator
Comparison operators are fully described in the JS Comparisons chapter.

JavaScript Logical Operators


Operator Description

&& logical and

|| logical or

! logical not
Logical operators are fully described in the JS Comparisons chapter.

JavaScript Type Operators


Operator Description

typeof Returns the type of a variable

instanceof Returns true if an object is an instance of an object type


Type operators are fully described in the JS Type Conversion chapter.

JavaScript Bitwise Operators


Bit operators work on 32 bits numbers.
Any numeric operand in the operation is converted into a 32 bit number. The result is
converted back to a JavaScript number.
Operator Description Example Same as Result

& AND 5&1 0101 & 0001 0001

| OR 5|1 0101 | 0001 0101

~ NOT ~5  ~0101 1010

^ XOR 5^1 0101 ^ 0001 0100

<< Zero fill left shift 5 << 1 0101 << 1 1010

>> Signed right shift 5 >> 1 0101 >> 1 0010

>>> Zero fill right shift 5 >>> 1 0101 >>> 1 0010


The examples above uses 4 bits unsigned examples. But JavaScript uses 32-bit signed
numbers.
Because of this, in JavaScript, ~ 5 will not return 10. It will return -6.
~00000000000000000000000000000101 will return
11111111111111111111111111111010
Bitwise operators are fully described in the JS Bitwise chapter.
JavaScript Data Types
JavaScript variables can hold many data types: numbers, strings,
objects and more:
var length = 16;                               // Number
var lastName = "Johnson";                      // String
var x = {firstName:"John", lastName:"Doe"};    // Object

The Concept of Data Types


In programming, data types is an important concept.
To be able to operate on variables, it is important to know something
about the type.
Without data types, a computer cannot safely solve this:
var x = 16 + "Volvo";
Does it make any sense to add "Volvo" to sixteen? Will it produce an
error or will it produce a result?
JavaScript will treat the example above as:
var x = "16" + "Volvo";
When adding a number and a string, JavaScript will treat the number as
a string.
Example
var x = 16 + "Volvo";
Try it Yourself »
Example
var x = "Volvo" + 16;
Try it Yourself »
JavaScript evaluates expressions from left to right. Different sequences
can produce different results:
JavaScript:
var x = 16 + 4 + "Volvo";
Result:
20Volvo
Try it Yourself »
JavaScript:
var x = "Volvo" + 16 + 4;
Result:
Volvo164
Try it Yourself »
In the first example, JavaScript treats 16 and 4 as numbers, until it
reaches "Volvo".
In the second example, since the first operand is a string, all operands
are treated as strings.
JavaScript Types are Dynamic
JavaScript has dynamic types. This means that the same variable can be
used to hold different data types:
Example
var x;           // Now x is undefined
x = 5;           // Now x is a Number
x = "John";      // Now x is a String
Try it yourself »

JavaScript Strings
A string (or a text string) is a series of characters like "John Doe".
Strings are written with quotes. You can use single or double quotes:
Example
var carName1 = "Volvo XC60";   // Using double quotes
var carName2 = 'Volvo XC60';   // Using single quotes
Try it yourself »
You can use quotes inside a string, as long as they don't match the
quotes surrounding the string:
Example
var answer1 = "It's alright";             // Single quote inside
double quotes
var answer2 = "He is called 'Johnny'";    // Single quotes inside
double quotes
var answer3 = 'He is called "Johnny"';    // Double quotes inside
single quotes
Try it yourself »
You will learn more about strings later in this tutorial.

JavaScript Numbers
JavaScript has only one type of numbers.
Numbers can be written with, or without decimals:
Example
var x1 = 34.00;     // Written with decimals
var x2 = 34;        // Written without decimals
Try it yourself »
Extra large or extra small numbers can be written with scientific
(exponential) notation:
Example
var y = 123e5;      // 12300000
var z = 123e-5;     // 0.00123
Try it yourself »
You will learn more about numbers later in this tutorial.
JavaScript Booleans
Booleans can only have two values: true or false.
Example
var x = 5;
var y = 5;
var z = 6;
(x == y)       // Returns true
(x == z)       // Returns false
Try it Yourself »
Booleans are often used in conditional testing.
You will learn more about conditional testing later in this tutorial.

JavaScript Arrays
JavaScript arrays are written with square brackets.
Array items are separated by commas.
The following code declares (creates) an array called cars, containing
three items (car names):
Example
var cars = ["Saab", "Volvo", "BMW"];
Try it Yourself »
Array indexes are zero-based, which means the first item is [0], second
is [1], and so on.
You will learn more about arrays later in this tutorial.

JavaScript Objects
JavaScript objects are written with curly braces {}.
Object properties are written as name:value pairs, separated by
commas.
Example
var person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};

Try it Yourself »
The object (person) in the example above has 4 properties: firstName,
lastName, age, and eyeColor.
You will learn more about objects later in this tutorial.

The typeof Operator


You can use the JavaScript typeof operator to find the type of a
JavaScript variable.
The typeof operator returns the type of a variable or an expression:
Example
typeof ""             // Returns "string"
typeof "John"         // Returns "string"
typeof "John Doe"     // Returns "string"
Try it Yourself »
Example
typeof 0              // Returns "number"
typeof 314            // Returns "number"
typeof 3.14           // Returns "number"
typeof (3)            // Returns "number"
typeof (3 + 4)        // Returns "number"
Try it Yourself »

Undefined
In JavaScript, a variable without a value, has the value undefined. The
type is also undefined.
Example
var car;    // Value is undefined, type is undefined
Try it Yourself »
Any variable can be emptied, by setting the value to undefined. The type
will also be undefined.
Example
car = undefined;    // Value is undefined, type is undefined
Try it Yourself »

Empty Values
An empty value has nothing to do with undefined.
An empty string has both a legal value and a type.
Example
var car = "";    // The value is "", the typeof is "string"
Try it Yourself »

Null
In JavaScript null is "nothing". It is supposed to be something that
doesn't exist.
Unfortunately, in JavaScript, the data type of null is an object.
You can consider it a bug in JavaScript that typeof null is an object. It
should be null.
You can empty an object by setting it to null:
Example
var person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
person = null;    // Now value is null, but type is still an object

Try it Yourself »
You can also empty an object by setting it to undefined:
Example
var person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
person = undefined;   // Now both value and type is undefined

Try it Yourself »

Difference Between Undefined and Null


undefined and null are equal in value but different in type:
typeof undefined           // undefined
typeof null                // object

null === undefined         // false


null == undefined          // true
Try it Yourself »

Primitive Data
A primitive data value is a single simple data value with no additional
properties and methods.
The typeof operator can return one of these primitive types:
string
number
boolean
undefined

Example
typeof "John"              // Returns "string"
typeof 3.14                // Returns "number"
typeof true                // Returns "boolean"
typeof false               // Returns "boolean"
typeof x                   // Returns "undefined" (if x has no
value)
Try it Yourself »

Complex Data
The typeof operator can return one of two complex types:
function
object
The typeof operator returns "object" for objects, arrays, and null.
The typeof operator does not return "object" for functions.
Example
typeof {name:'John', age:34} // Returns "object"
typeof [1,2,3,4]             // Returns "object" (not "array", see
note below)
typeof null                  // Returns "object"
typeof function myFunc(){}   // Returns "function"

Try it Yourself »
The typeof operator returns "object" for arrays because in JavaScript
arrays are objects.

ASSIGMENTS

In a file named quartsToLiters.html, write a defining table and a JavaScript program


that asks a user for a volume in quarts and then converts that value into liters. Your
program should correctly handle real numbers such as 7.54.
In a file named mileage.html, write a defining table and a JavaScript program to
compute the mileage of a vehicle. Your program should allow the user to enter the
beginning and ending odometer readings and the number of gallons of gasoline used
and should output the mileage in miles per gallon. Your program should correctly
handle real numbers such as 7.54.
TODO THINGS

Rounding results in assigments and to write down in notebook how to round results.

Reading chapter 6 for next week


6 CHAPTER SELECTION
How can a computer make decision?
It makes decision evaluating a condition, and if it is true, selecting one set of
statements to execute
What is a selection?
The decision making ability of the computer.
6.1 RELATIONAL OPERATORS
What is a condition in a selection statement?
It is a test that the computer does to select one set of statements or the other.
See examples in column 3 of the table above.
What is a Boolean expression?
Any expression that evaluates either true or false

What relational operator do we have?

Operator Name Example


< Less than If (I < 3)
> Greater than If (x > y)
<= Less than or equal to If (row <= end)
>= Greater than or equal to If (age>= 8)
== Equal to If (col == last)
!= Not equal to If (col == last)

What are the different forms of selection statements available in JavaScript, when
are they used and what is its templates?
Gives examples
Selection Used when Template Example
statement
If A true choice if (condition) if (balance>500) {
exists and the {statement; let interest = balance*0.03;
false choice does } balance += interest;
not exist }
Document.getElement
ById('output').
innerHTML= balance;
Desk check
700 21
721
if… else … A true choice if (condition) { let bonus;
exists and a false statements; if (sales <= 100) {
choice exists } bonus= 20;
else { }
statements; else {
} bonus= 100;
}
let salary = sales* 0.1 + bonus;
Desk check
Sales Bonus Salary
900 20 110
if … More than two if (condition) { let discount;
else if.. choices exist statements; if (cost < 100){
else… Each choice is } discount = 0.10;
based on else if }
different (condition) { else if (cost<250) {
variables or uses statements; discount= 0.15;
an operator } }
other than … else if (cost<400) {
equals(==) else { discount = 0.18;
statements; }
} else {
discount = 0.20;
}
cost *= (1- discount);
Desk check
Cost Discount
70 0.10
63
switch  More than two switch let registerDate;
choices exist (variable) { switch (classStanding) {
 Each choice is case case 'F':
based on the constValue1; registerDate = 'Nov 23';
same variable statements; break;
and uses equals break; case 'S':
(==) case registerDate = 'Nov 17';
 Comparison constValue2; break;
values are statements; case 'J':
integer or string break; registerDate = 'Nov 12';
… break;
default: case 'N':
statements; registerDate = 'Nov 6';
break; break;
} default:
registerDate= 'none';
alert('unknown class standing: '
classStanding);
break;
}
Document,getElementById('output')
.innerHTML = registerDate;
Desk check
classStanding registerDate
'J' 'Nov 12'

What are some unproperly usages of else statement?

Unnecesary and incorrect Correct and enough


usage Equivalent in English of
else in this usage
If (gender == 'M') { If (gender == 'M') { Everything else
// Code for males goes here. // Code for males goes
} here.
else if (gender == 'F') { }
// Code for females goes else {
here. // Code for females goes
} here.
}
let rate; let rate; Everyone else
if (age<18) { if (age<18) {
//Code for minors goes //Code for minors goes
here. here.
rate 0.4; rate 0.4;
} }
else if (age<58) else if (age<57)
// Code for adults goes her. // Code for adults goes her.
rate=0; rate=0;
} }
else if (age<100) { else {
// Code for senior citizens // Code for senior citizens
goes here. goes here.
} }

6.2 EVEN INTEGERS


What is an even integer?
It is a number that divided by 2 has a reminder equal than cero.

6.3 ODD INTEGERS

What must the result of the modulus operator be compared with in order to
determine an integer is even or od?
It must be compared with zero.

Why doesn´t comparing the result of the modulus operator with one work to
determine the integer is even or od?
Because it doesn’t work negative, odd integer, it works fine for positive integers, even
of odd.

What is the correct way to write code that takes action only if an integer is odd?
The proper way is to write the comparison with the not equal relational operator.
(!=)
Example:
// Correct check for odd integers
if ((number%2) != 0) {
document.getElementById('output').innerHTML = number + ' is odd';
}

What are the reasons to avoid using (&) operator to test if an integer is even?

It is not as straight forward as using the modulus operator.


It depends on the computer using two’s complement, binary representation for
integers.

6.4 QUADRATIC FORMULA

What is the quadratic equation and what part is the discriminant?

−b ± √ b2−4 ac
x=
2a
2
b −4 ac :discriminant
What is the function of the discriminant?

Its function is to discriminate between equations that have two, one, or zero roots.

Write a code that computes the real roots of a quadratic equation.


<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Quadratic formula</title>

<script>
/* Input: Three coeficients from a quadratic equation
*Processing: If they exist, compute the root of the root or roots of the equation.
* Output: The root or roots ot the equation or "undefined" if the don't exist.
*/
function quadratic(){
//Get the coefficients a, b, and c
let a= parseFloat(document.getElementById('aInputBox').value);
let b= parseFloat(document.getElementById('bInputBox').value);
let c= parseFloat(document.getElementById('cInputBox').value);

//Compute the root or roots of the quadratic equation if they exist.


let discr = b * b -4 * a * c;
let root1, root2;
if (discr >= 0){
let sq = Math.sqrt(discr);
root1 = (-b +sq)/(2*a);
root2 = (-b -sq)/(2*a);
}
// Display the roots to the user,
document.getElementById('output').innerHTML = root1 + ' ' + root2;
}
</script>
</head>
<body>
y= <input type = "text" id="aInputBox" size="3"> x<sup>2</sup> +
<input type="text" id="bInputBox" size="3"> x +
<input type="text" id="cInputBox" size="3">
<button type= "button" onclick="quadratic()">Compute Roots</button>
<div id="output"></div>
</body>
</html>

W3schools

 JavaScript Comparisons (Links to an external site.)


 JavaScript Conditions (Links to an external site.)
 JavaScript Switch
7 CHAPTER 7 LOGIC
What do we use to compare more than one comparison within an if statement?
We use the logical operators.

7.1 Logical operator


What are the logical operators?
They are operators to combine two or more comparisons in the condition of a single if
statement.
How many logical operators exist and how are they described?
There are four and a description of everyone is given in the undergoing table:
Operator Name Description
! Not Unary operator that
switches or reverses a true
value to false and a false
one to true
&& And Binary operator that
combines two conditions,
the combined condition is
true, if both are true,
otherwise combine
condition is false.
ll Inclusive or (Or) Binary operator that
combines two conditions,
the combined condition is
true, if either or both
conditions are true,
otherwise the combine
condition is false.
^ Exclusive or (Xor) Binary operator that
combines two conditions,
the combined condition is
true, if and only if one
condition is true and the
other is false, otherwise
the combine condition is
false.

What does it mean that the operator ! is unary operator?


This means that it operates one value.

Why does the operator Not have higher precedence?


Because this is a unary operator.

What is the template of a conditional statement with two conditions?

if (condition1 OPERATOR condition2) {


statements;
}
Example:
if (balance>0 && daySicnePayment > 30) {
approved= false;
}
7.2 Choosing a group

How should a program that chooses in which group a person or item belongs be
written?

In the example above there is a program that reads a girl’s age from the keyboard and
determines which class she should attend according the next table:

Age Class
Younger than 12 Primary
12 or 13 Beehive
14 or 15 Mia Maid
16 or 17 Laurel
18 or older Relief society

<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Which class</title>

<script>
/* Input: A girl´s age
*Processing: If statement to choose a class
* Output: Name of the class.
*/
function chooseClass(){
let age=parseInt(document.getElementById("age").value);
let group;
if (age<=11){
group = "Primary";
}
else if(age==12 || age== 13) {
group= "Beehive";
}
else if (age == 14 || age==15){
group= "Mia Maid";
}
else if (age == 16 || age==17){
group= "Laurel";
}
else {
group= "Relief society";
}
document.getElementById("output").innerHTML= group;
}
</script>
</head>
<body>
Please enter your age: <input type="text" id="age" size="3"><br>
<button type= "button" onclick="chooseClass()">Class</button>
<div id="output"></div>
</body>
</html>

How should a program to determine which scouting group a boy belongs be written?
According the next table:
Age Group
7 Tiger
8 Wolf
9 Bear
10 Webelos
Between 11 and 13, inclusive Boy Scout
Between 14 and 20, inclusive Venture
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Which group</title>

<script>
/* Input: A boy´s age
*Processing: If statement to choose a group
* Output: Name of the group.
*/
function chooseGroup(){
let age=parseInt(document.getElementById("age").value);
let group;
if (age<7){
group = "When you are 7 years old, you can become a Tiger Scout.";
}
else if(age==7) {
group= "Tiger";
}
else if (age ==8){
group= "Wolf";
}
else if (age == 9){
group= "Bear";
}
else if (age == 10){
group= "Webelos";
}
else if (11<=age && age<= 13){
group= "Boy Scout";
}
else if (14<=age && age<= 20){
group= "Venture";
}
else {
group= "You are too old to join scouting as a participant." + "Perhaps you
would like to volunteer as a leader.";
}
document.getElementById("output").innerHTML= group;
}
</script>
</head>
<body>
Please enter your age: <input type="text" id="age" size="3"><br>
<button type= "button" onclick="chooseGroup()">Class</button>
<div id="output"></div>
</body>
</html>
7.3 Disneyland autopia
How should a program to determine one person can drive a car in disneyland autopia
be written according requisites above?
Requisites:
54 inches (137 cm) or taller to drive alone
32 inches (81 cm) or taller and accompanied by a passenger 54 inches or taller.

<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Are you tall enough to drive on the Autopia?</title>

<script>
/* Input: The height of a driver and an optional passenger
*Processing: Determine if a driver and optional passenger may ride the Autopia
* Output: "Enjoy the ride!" or "Sorry, to drive a car on the autopia you must be
at least 54 inches tall or at least 32 inches tall and accompanied by a passenger who is
at least 54 inches tall"
*/
function checkHeight(){
let driver=parseInt(document.getElementById("driverBox").value);
let passenger=parseInt(document.getElementById("passengerBox").value);
let message;

if (driver >= 54 || (driver>=32 && passenger >=54)){


message = "Enjoy the ride!";
}
else {
message= "Sorry, to drive a car on the autopia you must be al least 54
inches tall of at least 32 inches tall and accompanied by a passenger who is at least 54
inches tall.";
}
document.getElementById("outputDiv").innerHTML= message;
}
</script>
</head>
<body>
<h1>Are you tall enough to drive on the Autopia?</h1>
Driver's height in inches:
<input type="text" id="driverBox" size="3" value="0"><br>
Passenger's height in inches:
<input type="text" id="passengerBox" size="3" value="0"><br>
<button type= "button" onclick="checkHeight()">Check Height</button>
<div id="outputDiv"></div>
</body>
</html>

7.4 Exclusive Or

7.5 Finding a range


Examples to select a range for a given value:
If the purchase amount is And the purchase amount Then the discount rate is
greater than or equal to is less than
0 $ 300 0%
$ 300 $ 600 2.0 %
$ 600 $ 1000 2.5 %
$ 1000 Infinity 3.0 %

// computes and returns a discounted purchase amount.


function getDiscountedAmount(purchase){
let rate;
if (purchase < 300) {
rate = 0;
}
else if (purchase < 600) {
rate = 0.02;
}
else if (purchase < 1000) {
rate = 0.025;
}
else {
rate = 0.03;
}
let discount = purchase * rate;
return purchase – discount;
}

It can be written like this also:

// computes and returns a discounted purchase amount.


function getDiscountedAmount(purchase){
let rate = 0;
if (purchase >= 0 && purchase < 300) {
rate = 0;
}
if (purchase >= 300 && purchase < 600) {
rate = 0.02;
}
if (purchase >=600 && purchase < 1000) {
rate = 0.025;
}
if (purchase >= 1000) {
rate = 0.03;
}
let discount = purchase * rate;
return purchase – discount;
}

7.6 Logical equivalences


What are the logical equivalences?
They are two different logical expressions that resolve to the same result, they are not
equal nor the same but equivalent.

What are some examples of logical equivalences?


Logical equivalence Example
Not Not a ↔ a If (!(!(age>8)))↔if (age>8)
a Or b ↔b Or a if (age > 8 || gender == “M”) ↔ if
(gender == “M” || age > 8)

What are some laws for logical equivalences?

7.7 Using the Morgan’s Law


What is the Morgan’s law?
It is a set of logical equivalences:
a. Not (a Or b) ↔ Not a And Not b
b. Not (a And b) ↔ Not a or Not b
c. a Or b ↔ Not (Not a And Not b)
d. a And b ↔ Not (Not a or Not b)
What is the code to print a list of students that do not have a GPA greater than 3.5
and at least 32 credits?
First, we could write the code for those that fulfill requirements:
if (gpa > 3.5 && credits >=32) {
document.getElementById(“outputDiv”).innerHTML= name + “ is on the dean’s list.”;

Now the code for those that do not fulfill requirements is written the same for those
that fulfill requisites but with and Not logical operator before the condition:

if(! (gpa > 3.5 && credits >=32)) {


document.getElementById(“outputDiv”).innerHTML= name + “ is on the average list.”;

Using the law of Morgan:


Not (a And b) ↔ Not a or Not b

if(! (gpa > 3.5)|| !( credits >=32)) {


document.getElementById(“outputDiv”).innerHTML= name + “ is on the average list.”;

Which can be simplified like this:


if( gpa <= 3.5|| credits <32) {
document.getElementById(“outputDiv”).innerHTML= name + “ is on the average list.”;

7.8 Advanced word Search


Example
Google Search Form

Google Search Query


CS5 Production Student premium OR adobe OR teacher -CS6 -ace -manual -training
Boolean Search Query
CS5 && Production && Student && (premium || adobe || teacher) && !CS6 && !ace
&& !manual && !training
7.9 Truth tables
What are truth table useful for?
They can help us to analyze logic, to write simpler Boolean expressions, and to prove
certain propositions about Boolean expressions.
Examples:
Given any two conditions a and b, show Not a, Not b, a And b, a Or b, a Xor b

1 2 3 4 5 6 7
a b !a !b a&&b a||b a^b
False False True True False False False
False True True False False True True
True False False True False True True
True True False False True True False

Given any two conditions a and b, show the result of (a Or b) And Not a

1 2 3 5 4
a b (a || b) && !a
False False False False True
False True True True True
True False True False False
True True True False False

1. We draw a truth table with a row for the heading and four rows for
boolean values.
2. In columns 1 and 2 we write the headings a and b and all possible
combinations of true and false.
3. In the headings row for columns 3, 4, and 5, we translate the logical
expression: (a Or b) And Not a into JavaScript operators: (a || b) && !a
4. We write the result of (a||b) in column 3. We write column 3 before
columns 4 and 5 because a || b is inside parentheses.
5. We write the result of !a in column 4. We write column 4 before column
5 because Not is a unary operator and has a higher precedence than
And.
6. Finally, in column 5 we combine the results of columns 3 and 4 using &&
so that column 5 contains the result of (a Or b) and Not a.
Given any two conditions a and b, prove that Not ( a Or b)↔ Not a And Not b
1 2 4 3 5 7 6
a b ! (a || b) ↔ !a && !b
False False True False True True True
False True False True True False False
True False False True False false True
True True False true false false false

Given any two conditions a and b, show the result of (a And b) Xor Not(a Or b)

1 2 3 6 5 4
a b (a&&b) ^ ! (a || b)
False False False True True False
False True False False False True
True False False False False True
True True True True False True

What is the equivalence of (a And b) Xor Not (a Or b)?


It is (a Xor b), it is shown in the table bellow:

1 2 3 6 5 4 8 7
a b (a&&b) ^ ! (a || b) ! (a^b)
False False False True True False True false
False True False False False True False True
True False False False False True False True
True True True True False True True false

Given any three conditions a, b, and c, prove (a Or b) Or c ↔ a Or (b Or c)

a b c (a || b) || c ↔ a || (b||c)
False False False False False False False
False False True False True True True
False True False True True True True
False True True True True True True
True False False True True True False
True False True True True True True
True True False True True True True
True True True True True True True

7.10 Common mistakes

Forgetting the left-hand side of a second comparison


Incorrect Correct
If (y==6 || 7) { If (y==6 || y==7) {
} }
If (y==(6 || 7)) {
}
If (y==6 ,7) {
}
If (y==(6, 7)) {
}
Forgetting &&
Incorrect Correct
If (10<x<20){ If (10<x && x<20){
} }
Mixing up the logical operators
Incorrect Correct
// This will always be true. Think about it. // Almost certainly you meant to write
If(x>10 ||x <20){ this:
} If (10<x && x<20){
}
// This will always be false // Almost certainly you meant to write
if (x==8 && x==9){ this:
} If(x==8 ||x ==9){
}
Unnecessary Comparisons
Incorrect Correct
if (age<8){ if (age<8){
} }
if(age>=8 && age<12){ else if(age<12){
} }
if(age>=12 && age<18){ else if(age<18){
} }
if (age>=18){ else {
} }
if (age<8){
}
else if(age>=8 && age<12){
}
else if(age>=12 && age<18){
}
else if (age>=18){
}

Review questions
1. The following if statement contains a logic error, not a syntax error. Rewrite it
so that it is correct. Assume the variable age already exists and holds a valid
number.
if (18 < age < 30) {
2. The following if statement contains a logic error, not a syntax error. Rewrite it
so that it is correct. Assume the variable age already exists and holds a valid
number.
if (18 < age || age < 30) {
3. The following if statement contains a logic error, not a syntax error. Rewrite it
so that it is correct. Assume the variable age already exists and holds a valid
number.
if (age == 18 && age == 19) {
4. After the following code executes, what value will the variable result hold?
5. let x = 2, y = 6, z = 5;
let result = (x < 3 && (y < 7 ^ z != 3))
6. Use DeMorgan’s law:  Not (a And b) ⇔ Not a Or Not b
to rewrite and simplify this if statement
if (!(x == 7 && y >= 0)) {

Which of the following is correct?


1. if (x != 7 || y < 0) {
2. if (x != 7 || y <= 0) {
3. if (x != 7 && y < 0) {
4. if (x == 7 && y >= 0) {
7. Use the advanced search at google to find on the internet a recipe for pizza that
doesn’t include tomato sauce. Besides the dough, what ingredients does the
recipe use?
8. Search the online gospel library at scriptures.lds.org to find the verses in the
scriptures with the phrase “word of my power”. Occasionally the search at
scriptures.lds.org doesn’t work. If that is the case, you could use the search at
lds.org or the advanced search at google and restrict your search to
site:scriptures.lds.org  How many verses did you find? Who is the “word of my
power”?
9. Use a truth table to prove that Not (a And b) ⇔ Not a Or Not b
10. Use a truth table to prove that Not (a Or b) ⇎ (Not a Or b)
Note that the symbol ⇎ means not equivalent.
11. Write a truth table for this Boolean expression: (a Or b) And Not (a Xor b) Does
the result seem familiar? Is it possible to rewrite this boolean expression more
simply and get the same result? What is the simplified expression?
12. Write a truth table for this Boolean expression: (a And b) Xor Not (b Or c)
106
Programming Assignments
Write a defining table and a program that asks the user to enter a month name
(January, February, etc.) and then outputs the number of days in the month. For
February, output “28 or 29 days”.
You work for a retail store that wants to increase sales on Tuesday and Wednesday,
which are the store’s slowest sales days. Write a defining table and then a program
that takes a customer’s subtotal as input and if the subtotal is greater than $50 and
today is Tuesday or Wednesday, subtracts 10% from the subtotal. Your program
should then compute and output the total amount due by adding sales tax of 6% to the
subtotal. Within your program, use this JavaScript code that will get the current day of
the week from your computer’s clock:
let dayOfWeek = new Date().getDay();
If you use the above code, the variable dayOfWeek will hold 0 if today is Sunday, 1 if
today is Monday, and so on to 6 if today is Saturday.
Write a defining table and then a program that determines if you can sleep in or not.
Your program should get all its input from your computer’s clock. On all weekdays
(Monday through Friday) that are not holidays, your program should output “Get up!”
On all other days (weekends and holidays), your program should output “Sleep in.” The
three holidays that your program must check for are January 1 (New Year’s Day), July 4
(U.S. Independence Day), and December 25 (Christmas). You don’t need to include
other holidays in your program because most other holidays do not occur on a fixed
day each year.
Within your program, use this JavaScript code that will get the current month, current
day of the month, and current day of the week from your computer’s clock:
let now = new Date();
let month = now.getMonth();
let dayOfMonth = now.getDate();
let dayOfWeek = now.getDay();
If you use the above code, the variable month will hold 0 if the current month is
January, 1 if February, and so on to 11 if December. The variable dayOfMonth will hold
1 for the first day of the month up to 28, 29, 30, or 31 for the last day of the month.
The variable dayOfWeek will hold 0 if today is Sunday, 1 if today is Monday, and so on
to 6 if today is Saturday.
107
Write defining table and then a program to determine if you and your date will be
allowed to eat in a fancy and fashionable restaurant. Your program should read two
integers from the keyboard, one that specifies your fashion measure from 1 to 10,
inclusive and one that specifies your date’s fashion measure from 1 to 10, inclusive. If
either of your fashion measures is 2 or less, your program should output “Not a
chance”. If either of your fashion measures is 8 or greater, your program should output
“Welcome”. If your fashion measures sum to more than 12 your program should
output, “Maybe”. Otherwise, your program should output “Unlikely”.
Write a defining table and then a program that determines what time a child should go
to bed. Your program must read a child’s age and the season (winter, spring, summer,
or fall) from the keyboard and output the child’s bedtime according to this table:
Age Season Bed Time
5 or younger summer, fall 8:30 p.m.
5 or younger winter, spring 8:00 p.m.
6 to 12 summer 9:30 p.m.
6 to 12 winter, spring, fall 8:30 p.m.
13 and older summer 10:30 p.m.
13 and older winter, spring, fall 9:30 p.m.
What percentage Programming Fundamentals in JavaScript, Chapter 7 "Logic", did you
read?

None

More than 0% but less than 50%

At least 50% but less than 75%

At least 75% but less than 100%

100%
Item at position 2
2
1 point
Item 2 is unpinned. Click to pin.
The following if statement contains a logic error, not a syntax error. Rewrite it so that it
is correct. Assume the variable age already exists and holds a valid number.
if (18 < age < 30) {
Question Blank
Item at position 3
3
1 point
Item 3 is unpinned. Click to pin.
The following if statement contains a logic error, not a syntax error. Rewrite it so that it
is correct. Assume the variable age already exists and holds a valid number.
if (18 < age || age < 30) {
Question Blank

The following if statement contains a logic error, not a syntax error. Rewrite it so that it
is correct. Assume the variable age already exists and holds a valid number.
if (age == 18 && age == 19) {
Question Blank

After the following code executes, what value will the variable result hold?
let x = 2, y = 6, z = 5;
let result = (x < 3 && (y < 7 ^ z != 3));

True && (true ^ true)


Ture && False
False
Question Blank
Item at position 6
6
1 point
Item 6 is unpinned. Click to pin.
Use DeMorgan’s law:  Not (a Or b) <=> Not a And Not b to rewrite and simplify this if
statement
if (!(x == 4 || y < 0))
Which of the following is correct?

if (x != 4 && y >= 0)

if (x != 4 || y > 0)

if (x == 4 && y < 0)

if (!(x == 4 || y < 0))


8 REPETITION
What does every loop include?
A Boolean condition.
While (condition) {
Statements;
}

for (initialization; condition; update){


statements;
}

What does the computer evaluate each time it needs to decide if it should repeat the
statement inside a loop?
It evaluates the loop’s boolean condition.

When does the computer repeat the statements inside the loop?
When the condition evaluates to true.

8.1 Pre-test and Post-test Loops


When is each of them used?
Post-test loops are not used frequently because they can be written as pre-test loops
How are loops categorized and what are their features?
They are categorized according the place the condition is located as pre-test and post-
test loops.
pre-test loops post-test loops.
Condition is before the loop Condition is after the loop
Condition is executed before statements Statements inside the loop are executed
inside the loop before the condition.
Statements inside the loop may be not The statements will be executed at least
executed if the condition is not true. once because they are before the loop
condition.

8.2 Counting and Sentinel Controlled Loops


How are loops categorized by their condition?
They are categorized as counting and as sentinel controlled loops.
What do counting and sentinel controlled loops cause the computer to and what do
their conditions check to?
Counting loop Sentinel controlled loop
Cause the computer to count from a start value to repeat statements until
an end value. some event occurs or the
computer encounters some
sentinel value.
Condition Condition
Check to See if the counting variable for the occurrence of that
has reached the end value event or that sentinel
value.

8.3 Repetition control structures


What are the ways to write a repetition control structure to cause a computer to
repeat statements?
The four ways are: while, for, for-in, and do-while.
Which of them have a condition and repeat the statements inside of them while the
condition is true?
While, for, and do-while loops.
How do for-in loop repeat the statements inside the loop?
Once for each attribute in an object.
When is each way used, what are their templates and examples?
Way When to use it Template Examples
While (post-test You need a simple While (condition) { let i=1;
loop) counting loop. Statements; while (i<3) {
You cannot use a } alert(i);
simple counting i++;
loop, so you must }
use a sentinel alert(“Done”);
controlled loop,
the sentinel must
be checked before
executing the
statements inside
the loop.
For () Though it is a for (initialization; for( let i=1; i<3; i++) {
Pre-test loop. shortened way of condition; update) alert(i);
writing a counting { }
while loop it is statements; alert(“Done”);
used when: }
You need a simple let i=
counting loop parseInt(document.
getElementById('start
InputBox').value);
for(; i<=5; i++) {
// statements to
repeated go here.
alert(i);
}
alert('Done');
for-in The statement in for (variable in let text = “”;
the loop must be object) { for (let part in
repeated once for statements; document) {
each element in an } // statements to be
object. repeated go here.
Text += part + '': ''
+ document [part] +
''<br>'';
}
document.getElement
ById('output').value=
text;
do while You can’t use a do { let i= 1;
simple counting statements; do{
loop, so you must } while(condition); alert(i);
use a sentinel i++;
controlled loop } while (i<3);
alert('Done');
The statements
inside the
loop must let alias, response;
be do {
executed //Get the user’s
before name.
checking alias= prompt(''What
the sentinel is your name? '');
/Ask the user if that is
really her name.
response =
prompt(''Are you sure
'' + alias + '' is your
name? '');
}while(response !=
''yes'');
//Say hello to the
user.
alert(''Hello'' + alias);

8.4 Simple counting loop


What loops can a programmer use to write a simple counting loop?
He can use both while or for loop
What is the code for a loop that ascends (count up), and for one that descends (count
down)?
ASCENDS:

let i= 1;
while (i<=3) {
alert(''leaf'');
i++;
}
DESCENDS:
for (let i=3; i>=1; i--) {
alert(''caterpillar'');
}

8.5 Zero-Based Counting Loop


Why do computer programmers write counting loops to begin at zero rather than one
(1)?
Because array elements are indexed starting with zero in C, C++, Java, and JavaScript.
Because zero-based counting loops are so common and useful in computer
programming.

How is a code written of zero-based counting loop that execute the statements inside
the loop exactly 3 times?
Example 1.
let i=0;
while (i<3) {
alert(''stem'');
i++;
}
Example 2

for(let i=0;i<3; i++) {


alert(blossom)

8.6 Skipping loop


What is the code to count some other number by using += or the -= operator?
Example 1:
let i =12
while (i>0) {
alert(“aphid”);
i -=4;
}
Example 2:
for (let i=0; i<5; i += 2) {
alert(“butterfly”);
}
8.7 Infinite loop
What causes a loop to be infinite?
Missing the updating part causes the loop to be infinite.

Code without update part (infinite loop) Code with update part
let i = 0; let i = 0;
while (i<5) { while (i<5) {
alert ('Hello'); alert ('Hello');
} i++;
}
for (let i= 0; i<5; ) { for (let i= 0; i<5; i+=2 ) {
alert ('Hello'); alert ('Hello');
} }

What loop can be used to avoid writing an infinite loop and why?
This is a for loop because the programmer will have to write the update part of the
loop at the same time, he writes the initialization and the condition parts
8.8 Compound interest
What is the code to calculate the balance of an account with compound interest?
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Compound interest</title>

<script>
/* Input:
* An amount to invest: balance
* The anual rate of growth: annual Rate
* The number of months to invest: numMonths
*Processing: Use a loop to compute the balance of an account after a bank has
paid interest for numMonths number on months.
* Output: The balance after numMonths have passed
*/
function futureValue(){
let balance= parseFloat(document.getElementById('balance').value);
let annualRate= parseFloat(document.getElementById('annualRate').value);
let numMonths= parseFloat(document.getElementById('months').value);
let monthlyRate = annualRate/12;
// For each month, compute the interest and add it to the balance.
for (let month=1; month<= numMonths; month++){
//Compute the interest for a month.
let interest= balance*monthlyRate;
//Round the interest to pennies.
interest = Math.round(interest*100)/100;
//Add the interest to the balance.
balance += interest;
}
// Display the resulting balance for theuser to see.
document.getElementById("output").innerHTML= 'Your balance after ' +
numMonths + ' months will be $' + balance;
}
</script>
</head>
<body>
Balance: <input type="text" id="balance" size="7"><br>
Annual growth rate: <input type="text" id="annualRate" size="5"><br>
Number of months: <input type="text" id="months" size="3"><br>
<button type= "button" onclick="futureValue()">Future Value</button>
<div id="output"></div>
</body>
</html>
8.9 Break
What does the break keyword cause the computer and when is it normally used?
It causes the computer to end a loop prematurely and it is used inside an if statement
that is inside the loop.

Write a code to allow user to input 10 values and to return the sum of the values but
stopping sum if the value entered is 0:

//Get 10 or fewer numbers from the user and adds them together.
function sum10(){
let sum=0;
for (let I = 0, i<10; i++) {
let n= parseFloat(prompt('Please enter a number'));
if (n==0) {
break;
}
alert(sum);
}
8.10 Prime numbers
What prime numbers are very important in?
They are very importing in computing, for example in hash code algorithms and data
encryption.

Write a code to determine if a number is prime:


<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Prime number</title>

<script>
/* Input: An integer
*Processing: determine if the given integer is prime or not.
* Output: _is prime OR_ in not prime
*/
function isPrime(){
let candidate= parseFloat(document.getElementById('integerBox').value);
// Count the number fo factors that evenly divide candidate.
let factorCount= 0;
for (let divisor=1; divisor<= candidate; divisor++){
let remainder = candidate%divisor;
if (remainder==0){
factorCount++;
}
}
// Determine the output and show it to the user.
let output;
if(factorCount==2){
output = candidate + 'is prime';
}
else {
output= candidate + 'is not prime';
}
document.getElementById("outputDiv").innerHTML= output;
}
</script>
</head>
<body>
Please enter an integer: <input type="text" id="integerBox"><br>
<button type= "button" onclick="isPrime()">Is prime Value</button>
<div id="outputDiv"></div>
</body>
</html>

8.11 Repetitive strings


What is the code to have a string with the pattern of counting by twos?

let output = '0';


let i=2;
while (i<=10) {
output += ', ' +i;
i+=2;
}
document.getElementById('displayDiv').innerHTML = output;

What does the code “output += ', ' +i;” perform and why?
It performs string concatenation and not addition because:
The starting value for the variable output is a string ('0')
The coma and space (', ') is also a string.

COMMON MISTAKES

Writing an infinite loop


Incorrect Correct
let i=0; let i= 0;
while (i<3) { while (i<3) {
alert(''Hello''); alert(''Hello'');
} i++;
}

// or

for (let i=0; i<3; i++) {


alert(''Hello'');
}

Writing a loop that never repeats


Incorrect Correct
for (let i=0, i>3, i++) { for (let i=0; i<3; i++) {
} }
// or
for (let i=0; i!=3; i++) {
}

Using comas to separate the parts of a for loop


Incorrect Correct
for (let i=0, i<5, i++) { for (let i=0; i<5; i++) {
} }

Forgetting braces when there is more than one statement inside a loop
Incorrect Correct
for (let i=0, i<n, i++) for (let i=0; i<n; i++) {
interest = balance * rate; interest = balance * rate;
balance += interest; balance += interest;
}

Placing a semicolon at the end of a while loop or for loop


Incorrect Correct
let i=0; let i=0;
while (i<3); { while (i<3) {
alert(''Hello''); alert(''Hello'');
i++; i++;
} }

for (let i=0; i<3; i++); { for (let i=0; i<3; i++) {
alert(''Hello''); alert(''Hello'');
} }

Chapter summary:
 Repetition id the control structure that a programmer uses to cause a
computer to repeat a group of statements.
 Loop is the informal term for repetition control structure.
 In a pre-test loop, the loop continuation condition is written at the top of the
loop, which causes a computer to check the condition before the computer
executes the statement in the loop.
 In a post-test loop, the loop continuation condition is written at the bottom of
the loop which causes a computer to execute the statements in the loop before
it checks the condition.
 A counting loop causes a computer to repeat a group of statements until a
counting variable reaches a desired number.
 A sentinel controlled loop causes a computer to repeat a group of statements
until an even (the sentinel) occurs.
 There are four styles of loops in JavaScript: while, for , for-in, and do-while.
 A while loop is a pre-test loop that is ofte used as a sentinel controlled loop
that causes a computer to repeat the statements inside it while a given
condition is true.
 A for loop is a pre-test loop that is used for writing simple counting loop.
 A do- while loop is a post-test loop that is often used as a sentinel controlled
loop.

1. Given the following JavaScript code, how many times will the computer display the
word "Flowers"?

for (let i = 3; i < 7; i++) {


alert("Flowers");
}
R. - Four times
2. Given the following JavaScript code, how many times will the computer display the
word "Apple"?

let i = 0;
let limit = 5;
while (i < limit) {
alert("Apple");
i += 2;
}
R. - It will display 3 times apple.
3. Given the following JavaScript code, how many times will the computer display the
word "Goodbye"?

for (let i = 0; i > 3; i++) {


alert("Goodbye");
}

R. - None times.
4. Given the following JavaScript code, how many times will the computer display the
word "Snow"?

let i = 0;
while (i < 3) {
alert("Snow");
}
R. - None because there is no an increment defined.
5. Write a while loop to count from 1 to 10.
let i=1;
while(i<11){
i++;
}
6. Write a for loop to count from 1 to 10.

for(i=1; i<11;i++){
}
7. Write a loop to count by threes from zero to nine. After the loop is finished, your
counting variable should hold the value 9.
let n;
for(i=0; i<=9;i+=3){
n =i;
}

8. Write a loop to count backwards from 90 to 81. After the loop is finished, your
counting variable should hold the value 81.
let n;
for(i=90; i>80;i--){
n =i;
}

9. Write a loop to count forwards by twos from the value in the variable first to the
value in the variable last. Assume the variables first and last already exist and hold
values.
for(i=v1; i<=v2;i+=2){
}

10. Write a loop to count backwards by twos from the value in the variable last to the
value in the variable first. Assume the variables last and first already exist and hold
values.
for(i=v2; i>=v1;i-=2){
}

11. Desk check the following code and then write a sentence describing what the code
does.
function func1() {
let c = "";
let a = parseInt(document.getElementById('integerBox').value);
let b = 100;
while (b >= 0) {
c += b + "<br>";
b -= a;
}
document.getElementById('outputDiv').innerHTML = c;
}

Desk Check
a b c
20

12. Desk check the following code and then write a sentence describing what the code
does. How does this code differ from the code in the previous example? Hint: consider
the indentation of the statements in the previous example compared to the
indentation of the statements in this example. Also, consider the names of the
variables in both examples. Which example is easier to read and desk check?

function countDown() {
let output = "";
let skip = parseInt(document.getElementById('integerBox').value);
let i = 100;
while (i >= 0) {
output += i + "<br>";
i -= skip;
}
document.getElementById('outputDiv').innerHTML = output;
}
Desk Check
skip i output
20

13. Desk check the following code and then write a sentence describing what the code
does.

function func4() {
let d = "Please enter an integer.";
let b = 38;
let c;
do {
c = parseInt(prompt(d));
if (c < b) {
d = "Too low. Please enter another integer.";
}
else if (c > b) {
d = "Too high. Please enter another integer.";
}
} while (c != b);
d = c + " is correct!";
alert(d);
}

Desk Check
b c d

25
60
38
129

14. Desk check the following code and then write a sentence describing what the code
does. How does this code differ from the code in the previous example? Hint: consider
the indentation of the statements in the previous example compared to the
indentation of the statements in this example. Also, consider the names of the
variables in both examples. Which example is easier to read and desk check?

function numberGuessGame() {
let message =
"I'm thinking of a number between 1 and 100.\n" +
"Try to guess it!\n" +
"Please enter an integer between 1 and 100.";
let answer = 38;
let guess;
do {
guess = parseInt(prompt(message));
if (guess < answer) {
message = guess +
" is too low. Please enter another integer.";
}
else if (guess > answer) {
message = guess +
" is too high. Please enter another integer.";
}
} while (guess != answer);
message = guess + " is correct!";
alert(message);
}

Desk Check
answer guess message

50
25
38

Programming Assignments
1. Write a defining table and program that reads an integer n from the keyboard and
then displays the word “sunshine” n times in a div.

2. Write a defining table and a program that reads a phrase and an integer n from the
keyboard and then displays that phrase n times in a div.

3. Write a defining table and a program that asks the user for an integer n and then
outputs all the integers between 1 and n, inclusive.

4. Write a defining table and a program that asks the user for an integer n and then
outputs the sum of all the odd integers between 1 and n, inclusive. For example, if a
user entered 10, your program would add 1 + 3 + 5 + 7 + 9 and output 25. If a user
entered 11, your program would add 1 + 3 + 5 + 7 + 9 + 11 and output 36.

5. Write a defining table and a program to output the five times table from 1 to 12 in
this format:
5x1=5
5 x 2 = 10

5 x 12 = 60
6. Write a defining table and a program to output all powers of 2 from 2 0 up to 231,
inclusive. In other words, your program should output this series: 1, 2, 4, 8, …
2147483648

7. Write a defining table and a program that outputs the first 25 numbers in this
Fibonacci series: 0, 1, 1, 2, 3, 5, 8, … 46368

8. Rewrite the number guessing game code found in review question 14 so that it
counts the number of guesses the user takes to guess correctly the answer.

9. Write a defining table and a program that asks the user for an integer n and then
outputs the following table.
n 2*n 3*n n*n n*n*n
1 2 3 1 1
2 4 6 4 8
3 6 9 9 27
⋮ ⋮ ⋮ ⋮ ⋮
n 2n 3n n2 n3

10. Write a defining table and a program that builds and displays a 12 by 12
multiplication table.

11. Write a defining table and a program that allows a user to enter ten numbers and
then computes and outputs the average of those numbers. The user interface for your
program should look similar to figure 8-4. Your program must use a loop to read the
ten numbers and compute the sum of those numbers.

W3SCHOOLS

 JS Loop For (Links to an external site.)


 JS Loop While (Links to an external site.)
 JS Breaks

What part of the loop must not be forgotten in order to avoid infinite loop?

loop Part that must not be forgotten


for while (i < 10) {
  text += "The number is " + i;
  i++;
}
If you forget to increase the
variable used in the condition, the
loop will never end. This will crash
your browser.
While for (statement 1;  statement
2;  statement 3) {
  // code block to be executed
}

If you omit statement 2, you must


provide a break inside the loop.
Otherwise the loop will never end.
This will crash your browser. Read
about breaks in a later chapter of
this tutorial.

9 CHAPTER 9. FUNCTIONS
How is a part of a program called?
It is called module.
What is a function?
It is the smallest module that performs actions and sometimes it is called a method.
How do functions work?
They work similar to mathematical functions. They took an argument and give results.
Check the next mathematical functions whose arguments is x:
f ( x )=2 x−1
CHAPTER OUTCOMES
 Write functions that accept and use parameters.
 Write code to return a value from a function to its call point.
 Write code to call a function and pass arguments to that function.
 Write code to store the result returned from a function in a variable.
 Distinguish between a parameter and an argument.
 Distinguish between displaying output for the user to see and returning a value
to be used by the program.
 Understand variable scope.
9.1 Advantages of functions
What are advantages of writing statements inside a function instead outside?

1. Control of execution - Statements inside a function will be executed


only when the function is called, not like statements that are inside html
tag script that are executed when a document is read into memory by a
browser.
2. Code reuse – A function can be executed again and again, each time this
is called in the program.
3. Less code - Because code can be reused.
4. Fewer coding mistakes – Less code means less opportunities to have
mistakes.
5. Better organization.
6. Easier to read and understand
7. Easier to debug
8. Faster execution – Because well written functions in programs use less
code, so it is executed faster.
9. Variable name reuse – Variables can be reused in different functions
because variables are local to function in which they are declared.
9.2 Writing a function
What is the template for a function?
The template is this:
function funtionName(parameter1, parameter2, … parameterN) {
statements;
return value;
}

How is called the first line of a function and what does it include?
It is called header or signature and it includes:
1. the keyword function
2. the function name
3. the parameter list
What are some rules to write the name of the function?
It has to begin with a letter, the underscore, or the dollar sign. Any number or letter
can be written after the beginning word. No spaces are permitted.

What does the parameter list contain?


It contains data, stored in variable, that the function needs to complete its task.

What is a parameter?
It is a variable whose value comes from outside the function.

What are the ways to get input into a function?


Asking the user for input through a pop-up message.
Through a text field.
Through the function’s parameters.

Why getting input from a parameter is more flexible than asking user for it?
Because the input through parameters can come from:
 The user
 A file on a hard drive
 The network
 A sensor
 Another function
What is the body of the function?
The statements inside it.

How long should a function be?


Less than a page (60 lines).
What has to be done to return a result from a function so that the result can be used
somewhere else in a program?
Type the keyword return followed by whatever value you want returned to the calling
function.

Example 1
Write the header for a function named drawCircle that takes three parameters: the x
and y values for the center of the circle and the radius of the circle, all in pixels.

function drawCircle(centerX, centerY, radius)

Example 2
Write a function (header and body) that computes and returns the average of three
numbers.
// Computes and returns the average of three numbers.
function average(a,b,c) {
let sum= a+b+c;
let avg= sum/3;
return avg;
}

Example 3

Write a function that takes two parameters and computes and returns the value of this
equation: f(a,r)= a * r(1+r)

function formula(a,r) {

let result= a*(1+r);


return result;
}

9.3 Calling a function


What is calling or invoking a function?
It is the act of causing the computer to execute the code in that function.

How is a function called?


By writing the name of the function followed by the data, known as arguments, which
the function will need to perform its task.

What can an argument be?


A number, a string or a variable.
What should it be taken in count if the argument is a variable?
That these variables must not have the same name than parameters in function.

What about the order of parameters in a function and arguments to call a function?
They must be on the same place.

What is the template for calling a function?


functionName(arg1, arg2, …argN);

Example
Write the code to call a function that has this header:
function drawCircle(centerX, centerY, radius)

function run() {
// Get three values from the user.
let x= parseInt(document.getElementById('xInputBox').value);
let y= parseInt(document.getElementById('yInputBox').value);
let radius= parseInt(document.getElementById('radiusInputBox').value);

// Call the drawCircle function.


drawCircle(x,y,radius);

What is the code to call a function and assign its result to a variable so that the result
can be used later?

The code is this that follows:

varName= functionName(arg1, arg2, … argN);

Example:

Write code to call a function named computeCaloriesBurned and store the result
returned from that function in a variable named calories. The function has this header:

function computeCaloriesBurned(distance, elevation, wight)

function testCalories(){
let dist=2000;
let elev = 750;
let weight = 72.6;

// Call the computeCaloriesBurned function.

calories = computeCaloriesBurned(dist, elev, weight);

// Display the calories for the user to see.

document.getElementById('outputDiv').innerHTML= calories;

Example:
Write code to call the square root function in the Math object and assign the result
returned from it to a variable named r. The square root function has this header:

function sqrt(x)

function testSqrt() {
//Get a number from the user.
let value = parseFloat(document.getElementById('inputBox').value);

// Call the Math.sqrt function.


let r= Math.sqrt(value);

// Display the square root for the user to see.

document.getElementById('outputDiv').innerHTML = r;

What is a call point?


It is a line of code that calls a function

What does a return statement inside a function cause the computer to do when it is
executed?
It causes the computer to do three things:

1. The return statement causes the computer to return a value, which is


often a number, to the call point. If the call point includes a variable and
the assignment operator (=), the computer will store the returned value
in that variable.
2. The return statement causes the computer to terminate the called
function or in other words to stop executing the code in the body of the
called function.
3. The return statement causes the computer to resume executing code at
or after the call point.
9.4 Variable scope

What does the scope of a variable determine?


It determines how long that variable exists and where it can be used.

Programming Assignments

1. Rewrite the number guessing game code found in review question 14 of chapter 8
so that it
a) is inside a function with this header:
function numberGuessGame()
which is called when a user clicks a Play button

b) chooses a different pseudo random number between 1 and 100 each time it runs
c) counts the number of guesses the user takes to correctly guess the answer

2. Create an HTML document, which contains a text field, a button, and a div. Label the
first text field “Fahrenheit” and put the text “Celsius” on the button. Write two
functions with these headers:

function doInputOutput()
function fahrToCels(fahr)

The first function (doInputOutput) must be called from the onclick attribute of the
button and must do the following:
a) get a temperature in Fahrenheit from the text field
b) call the second function (fahrToCels)
c) store the value returned by fahrToCels in a variable
d) output the value returned by fahrToCels to the div for the user to see

The second function (fahrToCels) must


a. take a temperature in Fahrenheit as a parameter
b. calculate the corresponding Celsius temperature
c. return the Celsius temperature
In other words, the second function (fahrToCels) must not gather any input from a user
and must not output anything for a user to see. Instead, it must calculate and return
the result, which makes this second function very reusable in other projects.

3. Create an HTML document, which contains two text fields, a button, and a div. Label
the first text field “Temperature”, label the second “Wind Speed”, and put the text
“Wind Chill” on the button. Write two functions with these headers:

function doInputOutput()
function windChill(tempF, speed)

The first function (doInputOutput) must be called from the onclick attribute of the
button and must do the following:
get a temperature from the first text field
get a wind speed from the second text field
call the second function (windChill)
store the value returned by windChill in a variable
output the value returned by windChill to the div for the user to see
The second function (windChill) must
a. take a temperature in Fahrenheit as a parameter
b. take a wind speed in miles per hour as a parameter
c. calculate the wind chill factor as a temperature in Fahrenheit
d. return the wind chill factor in Fahrenheit

In other words, the second function (windChill) must not gather any input from a user
and must not output anything for a user to see. Instead, it must calculate and return
the result, which makes this second function very reusable in other projects.

The formula for computing the wind chill factor is


f = 35.74 + 0.6215 t − 35.75 s0.16 + 0.4275 t s0.16
f =35.74+ 0.6215∗t−35.75∗s0.16 +0.4275∗t∗s0.16

where f is the wind chill factor in Fahrenheit, t is the air temperature in Fahrenheit,
and s is the wind speed in miles per hour at five feet above the ground.

4. Create an HTML document, which contains two text fields, a button, and a div. Label
the first text field “Temperature”, label the second “Relative Humidity”, and put the
text “Heat Index” on the button. Write two functions with these headers:

function doInputOutput()
function heatIndex(tempF, humid)

The first function (doInputOutput) must be called from the onclick attribute of the
button and must do the following:
a. get a temperature from the first text field
b. get a relative humidity from the second text field
c. call the second function (heatIndex)
d. store the value returned by heatIndex in a variable
e. output the value returned by heatIndex to the div for the user to see

The second function (heatIndex) must


a. take a temperature in Fahrenheit as a parameter
b. take a relative humidity between 0% and 100% as a parameter
c. calculate the heat index as a temperature in Fahrenheit
d. return the heat index in Fahrenheit

In other words, the second function (heatIndex) must not gather any input from a user
and must not output anything for a user to see. Instead, it must calculate and return
the result, which makes this second function very reusable in other projects.

The formula for computing the heat index is


i=−42.379+2.04901523 t+10.14333127 r−0.22475541tr−0.00683783 t 2 −0.05481717 r 2+ 0.00122874 t 2
where i is the heat index in Fahrenheit, t is the air temperature in Fahrenheit, and r
is the relative humidity.
Figure 9-4 shows a triangular prism. The volume of a triangular prism can be
calculated by multiplying the area of the triangular face by the length of the prism. In
other words
volume = triangleArea * length

Write a program that calculates the volume of a triangular prism. Your program
must allow the user to enter the three side lengths of the triangular face and the
length of the prism. Your program must include these three functions:
a triangular prism
Figure 9-4: A triangular prism

function doInputOutput()
function prismVolume(a, b, c, length)
function triangleArea(a, b, c)

The first function (doInputOutput)


takes no parameters
is called from the onclick attribute
gets four numbers from the user
calls the prismVolume function
displays the result to the user

The second function (prismVolume)


takes four parameters
calls the triangleArea function
computes the volume of a prism
returns the volume

The third function (triangleArea)


takes three parameters
computes the area of a triangle
returns the area
Hint: use the triangleArea function that is written in this chapter.

Figure 9-5 shows a very basic house. Notice that the roof space of the house is a
triangular prism and the living space of the house is a rectangular prism. Write a
program that calculates the total volume of the house, including the volume of the
roof space. Your program must allow the user to enter the width, depth, height, and
sweep as shown in figure 9-5. Here are some useful formulas:
a simple house
Figure 9-5: A simple house
houseVolume = livingVolume + roofVolume
livingVolume = width * depth * height
roofVolume = triangleArea * width
triangleArea = √s(s−a)(s−b)(s−c)
s = a + b + c2

Your program must include these five functions:

function doInputOutput()
function houseVolume(width, depth, height, sweep)
function livingVolume(width, depth, height)
function roofVolume(width, depth, sweep)
function triangleArea(a, b, c)

The first function (doInputOutput)


takes no parameters
is called from the onclick attribute
gets four numbers from the user
calls the houseVolume function
displays the house volume to the user

The second function (houseVolume)


takes four parameters
calls the livingVolume function
calls the roofVolume function
computes the house volume by adding the living volume and the roof volume
returns the house volume

The third function (livingVolume)


takes three parameters
computes and returns the volume of the living space

The fourth function (roofVolume)


takes three parameters
calls the triangleArea function
computes and returns the volume of the roof
The fifth function (triangleArea)
takes three parameters
computes and returns the area of a triangle
Hint: use the triangleArea function that is written in this chapter.
155

Create an HTML document that looks similar to figure 9-6. Write two functions with
these headers:

function doFV()
function computeFutureValue(principal, annualRate, years, periodsPerYear)

The user interface for an investment calculator


Figure 9-6: The user interface for an investment calculator.

The first function (doFV)


takes no parameters
is called from the onclick attribute
gets input from the user
calls the computeFutureValue function
displays the result to the user

The second function (computeFutureValue) computes and returns the future value
of an investment. The formula for computing the future value of an investment is: f =
a (1 + r)n where f is the future value, a is the investment amount sometimes called the
principal, r is the growth rate per period, and n is the total number of periods
throughout the life of the investment.
156

Create an HTML document that looks similar to figure 9-7. Write four functions with
these headers:

function doPayment()
function doBalance()
function computePayment(principal, annualRate, years, periodsPerYear)
function computeBalance(principal, annualRate, years, periodsPerYear,
numberOfPaymentsPaidToDate)

The user interface for a loan calculator


Figure 9-7: The user interface for a loan calculator.

The first two functions (doPayment and doBalance)


take no parameters
are called from an onclick attribute
get input from the user
call the computePayment or the computeBalance function
display a result to the user

The computePayment function computes and returns the monthly payment for a
loan with a fixed annual interest rate. The formula for computing a loan payment is
p = ar 1 − (1 + r)−n 

where p is the payment per period, a is the loan amount, r is the interest rate per
period, and n is the total number of periods throughout the life of the loan.

The computeBalance function computes and returns the balance for a loan with a
fixed annual interest rate. The formula for computing the balance of a loan after d
payments have been made is
b = a (1 + r)d −  p ((1 + r)d − 1) r

where b is the balance or payoff amount, a is the loan amount, r is the interest rate
per period, p is the payment per period, and d is the number of payments paid to date.

What are the three categories of variable scope there are within JavaScript and their
features?

JavaScript Variable Scope


Block Function Global
Keyword Let Var let or var
Where to declare Inside a block Inside a function Outside all
functions
Owner The block where The function where The JavaScript
the variable is the variable is program, or stated
declared declared more accurately,
the HTML file that
contains the script
tag where it is
declared
Lifetime Only as long as its Only as long as its As long as its
containing block is containing function containing HTML
executing is executing file is loaded in the
computer’s
memory.
Where usable Only inside the Only inside the In all functions in
block where it is function where it is the JavaScript
declared declared program

Classify variables in the next example according to their scope

Example
let attempts;
function squareArea(length) {
let area=length*length;
return area;
}

function rectangleArea(width, length) {


let area= width*length;
return area;
}

Variable Scope
attempts Global
length function
width function
area Block

Why can the same name of variable be used in different functions?


Because function and block variables are visible only within the function where they
are declared. Variables with the same name in different functions are entirely separate
and do not conflict with each other in any way because the scope of each variable is
within the block or function where it is declared.

9.5 Pseudo random Integer


What is the code to obtain a pseudo random integer that is in the range min inclusive
to max exclusive, [min,max), calling both the random and floor functions from the
Math object?
Example

function randomInteger() {
let min =5;
let max=11;

// Call the Math.random and Math.floor functions.

let r = min + Math.floor(Math.random()*(max-min));

// Display the random integer for the user to see.


document.getElementById('outputDiv').innerHTML=r;

9.6 Code Reuse


Which are the most reusable functions?
They are those that just perform calculations and do not perform user input and
output.
In the next example describe which function performs calculations and which just
gets the user input and displays the result to the user.

<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>All the integers from one to the one you wrote</title>

<script>
/* Input: An integer.
*Processing: Determine if the integer is even or not
* Output: A message stating if the integer is even or not
*/
function doInputOutput(){
let number = parseInt(document.getElementById("numberInputBox").value);
let result= isEven(number);
document.getElementById("outputdiv").innerHTML= number + " is even: " +
result;
}

//Return true if value is an even


//integer; otherwise returns false.
function isEven(value) {
if((value%2)==0){
return true;
}
else {
return false;
}
}
</script>
</head>
<body>
Please enter an integer:<input type="text" id="numberInputBox">
<button type= "button" onclick="doInputOutput()">Is Even?</button>
<div id="outputdiv"></div>
</body>
</html>

Function highlighted with red get the input user, call the function isEven and display
the output to the user.

Function highlighted with blue perform calculations.

In the example bellow, why is the if statement omitted?


Because the isEven function returns a Boolean value, we can write it without the if
statement. Eliminating the if statement makes the function easier to test because the
function will contain only one possible path of execution instead of two.

9.7 Area of a triangle

Hero n' s formula


A=√ s (s−a)(s−b)(s−c)
a , b ,∧c :lenghts of the three sides of thetriangle
s :semiperimeter of the triangle
a+ b+c
s=
3
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Example 11</title>

<script>
/* Input: No user input
*Processing: Compute the area of the triangle with side lenghts 4, 2, and 5
* Output: The area of the triangle
*/
function testTriangle(){
let r = triangleArea(4,2,5);
document.getElementById("outputdiv").innerHTML= r;
}

//Computes and returns the area of a


//triangle with side lengths a,b, and c.
function triangleArea(a,b,c) {
let s=(a+b+c)/2;
let area=Math.sqrt(s*(s-a)*(s-b)*(s-c));
return area;
}
</script>
</head>
<body>
<button type= "button" onclick="testTriangle()">Test</button>
<div id="outputdiv"></div>
</body>
</html>
9.8 Surface Area of a pyramid

b2 2
e=
√2
+h
e : edge length of the pyramid
SAS= √ s( s−e)( s−b)(s−e)

SAS: surface area of a side


SAP=4∗SAS
SAP: surface area of a pyramid

<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Example 11</title>

<script>
/* Input: No user input
*Processing: Compute the suface area of the triangular faces of a regular
pyramid that has base 8 and height 7.
* Output: The surface area of the pyramid
*/
function testPyramid(){
let pa = pyramidSurfaceArea(8,7);
document.getElementById("outputdiv").innerHTML= pa;
}

//Computes and the surface area of the


//four triangular faces of a regular pyramid
// with the specified base length and height.
function pyramidSurfaceArea(base,height) {
let edge=Math.sqrt(base*base/2+height*height);
let triArea=triangleArea(base,edge,edge);
let pyramidArea= 4*triArea;
return pyramidArea;
}
//Computes and returns the area of a
//triangle with side lengths a,b, and c.
function triangleArea(a,b,c) {
let s= (a+b+c)/2;
let area= Math.sqrt(s*(s-a)*(s-b)*(s-c));
return area;
}
</script>
</head>
<body>
<button type= "button" onclick="testPyramid()">Test</button>
<div id="outputdiv"></div>
</body>
</html>

9.9 How long to invest


What is the code to calculate the time needed in order for an initial amount of money
to become greater until it gets a final desired amount?

Example: How many months will I need to invest $100 at 6% fixed annual growth rate
compounded monthly in order for my investment to grow to $103?
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Example 13</title>

<script>
/* Input: No user input
*Processing: Determine the numberj of months required to grow an initial
investment from $100 to at least 103$ if it grows at an anual rate of 6%.
* Output: the number of months
*/
function testInvest(){
let m = determineMonths(100,0.06,103);
document.getElementById("outputdiv").innerHTML= m;
}

//Computes and the number of months


//needed for principal invested at a constant annual rate to grow to a targert
amount
function determineMonths(principal,annualRate,target) {
let monthlyRate = annualRate/12;
let balance=principal;
let month=0;
//Repeat while the balance of the investemt is less than the target.
while (balance<target) {
let interest=Math.round(balance*monthlyRate*100)/100;
balance += interest;
month++;
}
return month;
}

</script>
</head>
<body>
<button type= "button" onclick="testInvest()">Test</button>
<div id="outputdiv"></div>
</body>
</html>
9.10 Greatest common divisor
What is the greatest common divisor (gcd)?
It is the largest positive integer that divides two or more number without remainder.
What is the algorithm discovered by Euclid to compute gcd?

Given two integers:


1. Divide 102 by 18 to get a quotient of 5 and a remainder of 12,
2. divide 18 by 12 to get a quotient of 1 and a remainder of 6,
3. divide 12 by 6 to get a quotient of 2 and a remainder of 0
4. the remainder 0 means the greatest common divisor of 102 and 18 is 6.

What is the code for Euclid’s method?

<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Example 13</title>

<script>
/* Input: No user input
*Processing: Determine the GCD of -24 and 472
* Output: the GCD
*/
function testGCD(){
let x=-24;
let y =472;
//Calling the gcd function
let divisor= gcd(x,y);
document.getElementById("outputdiv").innerHTML= divisor;
}

//Find and returns the GCD of two integers a and b.


function gcd(a,b){
// Ensure a and b are not negative.
a=Math.abs(a);
b=Math.abs(b);
//Ensure a is greater than or equal to b.
if (a<b){
let swap=a;
a=b;
b=swap
}
// Repeat until the computer finds the greatest common divisor.
do{
let r=a%b;
a=b;
b=r;
} while (b!=0);
return a;
}

</script>
</head>
<body>
<button type= "button" onclick="testGCD()">Test</button>
<div id="outputdiv"></div>
</body>
</html>

Common mistakes
Putting a space in a function’s name
Incorrect Correct
Function check Answer() { function checkAnswer(){
} }
Forgetting the opening of closing curly brace
Incorrect Correct
function sum(x,y,z){ function sum(x,y,z){
let s= x+y+z; let s= x+y+z;
return s; return s;
}
Re-declaring of re-assigning parameters
Incorrect Correct
function getDiscountRate(birthday, gpa){ function getDiscountRate(birthday, gpa){
// Wrong! Don’t re-declare nor assign
parameters. let birthYear = birthday.getFullyear();
let birthday= new Date(“3/17/1995”); let currYear = new Date().getFullyear;
let gpa = prompt(“What is your GPA?”); let age = currYear-birthyear;
late rate;
let birthYear = birthday.getFullyear();
let currYear = new Date().getFullyear; return rate;
let age = currYear-birthyear; }
late rate;

return rate;
}
Confusing the concepts of return and output
Return means to return a value to the call point of a function. This is entirely
internal to a program, and the user will not see anything because of a return
statement. To return a result from JavaScript function, use the keyword return.

Output means to show a vale to the user. In JavaScript output is done by calling
alert, document.write, or assigning a value to the innerHTML attribute of a div
(document.getElementById(“resultDiv”).innerHTML =x;).

JS Functions

4. Create an HTML document, which contains two text fields, a button, and a div. Label
the first text field “Temperature”, label the second “Relative Humidity”, and put the
text “Heat Index” on the button. Write two functions with these headers:
function doInputOutput()
function heatIndex(tempF, humid)
The first function (doInputOutput) must be called from the onclick attribute of the
button and must do the following:
1. get a temperature from the first text field
2. get a relative humidity from the second text field
3. call the second function (heatIndex)
4. store the value returned by heatIndex in a variable
5. output the value returned by heatIndex to the div for the user to see
The second function (heatIndex) must
1. take a temperature in Fahrenheit as a parameter
2. take a relative humidity between 0% and 100% as a parameter
3. calculate the heat index as a temperature in Fahrenheit
4. return the heat index in Fahrenheit
In other words, the second function (heatIndex) must not gather any input from a user
and must not output anything for a user to see. Instead, it must calculate and return
the result, which makes this second function very reusable in other projects.
The formula for computing the heat index is
i = −42.379 + 2.04901523 t + 10.14333127 r − 0.22475541 t r − 0.00683783 t2 −
0.05481717 r2 + 0.00122874 t2 r + 0.00085282 t r2 − 0.00000199 t2 r2
where i is the heat index in Fahrenheit, t is the air temperature in Fahrenheit, and r is
the relative humidity.
-229.9396172
355.22304

6. Figure 9-5 shows a very basic house. Notice that the roof space of the house is a
triangular prism and the living space of the house is a rectangular prism. Write a
program that calculates the total volume of the house, including the volume of the
roof space. Your program must allow the user to enter the width, depth, height, and
sweep as shown in figure 9-5. Here are some useful formulas:

house=living room+roofVolume
livingVolume=width∗depth∗height
roofVolume=triangleArea∗width
triangleArea=√ s (s−a)( s−b)( s−c)
a+ b+c
s=
2
Your program must include these five functions:
function doInputOutput()
function houseVolume(width, depth, height, sweep)
function livingVolume(width, depth, height)
function roofVolume(width, depth, sweep)
function triangleArea(a, b, c)

The first function (doInputOuput)

a. Takes no parameters
b. is called from the onclick attribute
c. gets four numbers from the user
d. calls the houseVolume function
e. displays the house volume to the user
The second function (houseVolume)

a. takes four parameters


b. calls the livingVolume function
c. calls the roofVolume function
d. computes the house volume by adding the living volume and the roof volume
e. returns the house volume.

The third function (livingVolume)

a. takes no parameters
b. computes and returns the volume of the living space
The fourth function (roofVolume)
a. takes three parameters
b. calls the triangleArea function
c. computes and returns the volume of the roof
The fifth function(triangleArea)

a. takes three parameters


b. computes and returns the area of a triangle
Hint: Use the triangleArea function that is written in this chapter.

7. Create an HTML document that looks similar to figure 9-6. Write two functions with
these headers:
function doFV()
function computeFutureValue(principal, annualRate, years, periodsPerYear)

The first function (doFV)


a) takes no parameters
b) is called from the onclick attribute
c) gets input from the user
d) calls the computeFutureValue function
e) displays the result to the user
The second function (computeFutureValue) computes and returns the future value
of an investment. The formula for computing the future value of an investment
is:  f = a (1 + r)n  where f is the future value, a is the investment amount sometimes
called the principal, r is the growth rate per period, and n is the total number of
periods throughout the life of the investment.
8. Create an HTML document that looks similar to figure 9-7. Write four functions with
these headers:

function doPayment()
function doBalance()
function computePayment(principal, annualRate, years, periodsPerYear)
function computeBalance(principal, annualRate, years, periodsPerYear,
numberOfPaymentsPaidToDate)

The first two functions (doPayment and doBalance)

a) take no parameters
b) are called from an onclick attribute
c) get input from the user
d) call the computePayment or the computeBalance function
e) display a result to the user

The computePayment function computes and returns the monthly payment for a loan
with a fixed annual interest rate. The formula for computing a loan payment is

ar
p=
1−(1+r )−n

where p is the payment per period, a is the loan amount, r is the interest rate per
period, and n is the total number of periods throughout the life of the loan.
The computeBalance function computes and returns the balance for a loan with a fixed
annual interest rate. The formula for computing the balance of a loan after d payments
have been made is

d p ( ( 1+r )d −1)
b=a(1+ r) −
1−(1+r )−n
where b is the balance or payoff amount, a is the loan amount, r is the interest rate per
period, p is the payment per period, and d is the number of payments paid to date.

10 CHAPTER 10. ARRAYS


What is an array?
It is a collection of variables of the same data type.

How is called each variable in an array and what is the subscript of a variable?
They are called elements and a subscript of a variable is a unique index which denotes
the element´s location within the array.

What is the advantage of using arrays?


It is that all the variables can be declared, created or passed to a function as a whole,
and each element can be still accessed by using the element’s index.

Chapter outcomes
To be able to
 Declare, create, and populate an array.
 Write code to access a single value withing an array.
 Write a loop to progress every element in an array.
 Write code to sort search an array.
 Use the methods in the array object to process arrays.

10.1 Declaring an array


How is an Array declared?
It is declared by writing the keyword var or let followed by the array’s name.
Template:
let arrayName;

Example 1

let data;
let scores;

10.2 Creating an Array

What is the keyword to create an array?


Template:
arrayName= new Array(size);
Example:
// create ana array that holds 6 elements.

data= new Array(6);

How can be combined both array declaration and array creation in a single
statement?

Example 3
//Declare and create an array that holds 25 elements.
let scores = new Array(25);

Example 4
// Get a length from the user and declare and create an array
// that holds the number of elements specified by the user.
let len= parseInt(document.getElementById(“len”).value);

Len Prices
8
[0] [1] [2] [3] [4] [5] [6] [7]
How is it possible to declare, create, an initialize the elements in an array in a single
JavaScript statement?
Template
let arrayName= [value0, value 1, …. valueN];
Example 5
let measures = [4.7, -3, 2.1, 0, 7.2];
Samples
4. -3 2. 0 7.2
7 1
[0] [1] [2] [3] [4]

10.3 Array length

What is the attribute that arrays automatically have and what is it?
It is attribute length, which is the number of elements contained in the array.

Template
arrayName.length

Example 6
let date = new Array(8);
let sizes = [4.7, 5.8, 2.1, 3.9, 7.2];
document.getElementById(“div1”).innerHTML= data.length;
document.getElementById(“div2”).innerHTML= sizes.length;

10.4 Accessing an element


What is the way to access and element withing an array?
The name of the array has to be written and the index of the element within brackets.
What values does index take in array?
Values between 0 and positive infinite
Template:

arrayName[index]

Example 7

let data= new Array(6);


data[0]=-4.3;
data[1]=parseFloat(document.getElementById(“input1”).value);
.
.
.
document.getElementById(“output”).innerHTML= data[4];
.
.
if(data[5]>6.3) {
document.getElementById(“error”).innerHTML= “Data value is too high”;
}

10.5 Filling an Array


How is it possible to have the computer initialize all the elements in an array to some
value (usually zero)?
An array has to be declared. A function has to be created with a loop that assign a
value to each index of the array. This function has to be called by the name of the
function and the value that will be stored in each index of the array.

Example 8
let list = new Array(80);
fill(list, 7);

// Fills the specified array with the value x.

function fill(list, x) {
// For each index in the array named list,

for (let i=0; i<list.length; i++) {


// store the value in x in the array.
list[i]=x;
}
}
10.6 Filling an array with a Ramp

What is the code to fill an array with a ramp?

Example 9
// Fills the specified array with constantly increasing values from 0 to list.legth -1,
inclusive.
function ramp(list){
// For each index in the array named list,
for (let i=0; i<list.length; i++) {
// store the value in I in the array.
list[i]=i;
}
}

What is the code for a reverse ramp?

Example 10

// Fills the specified array with constantly decreasing values from list.length-1 to 0,
inclusive.

function reverseRamp(list){
let high = list.length-1;
for (let i=0; i<list.length; i++) {
list[i]= high-1

10.7 Reversing an Array


What is the code for reversing the order of the elements in an Array?

Example 11

//Reverses the contents of the specified array.

function reverse(list) {
let left=0;
let right = list.length-1;

while (left<right) {

// Exchange two elements.

let swap= list[left];


list[left]= list [right];
list [right] = swap;

// Move the indexes toward the center.


left ++;
right--;

10.8 Summing the values in an Array


What is the function to sum elements stored in an Array?

Example 12

//Returns the sum of the values stored in an Array

function sum(list) {
let s=0;
for (let i=0; i<list.length; i++) {
s += list[i];
}
return s;
}
10.9 Finding a value (linear search)

How is called the value to be found?


It is called the key.
How is a linear search done?
It is done by comparing each element in the array with the key until the key is found in
the array or the end of the array is reached.

What are advantages and disadvantages of linear search?


It is simple and easy to code, but it is too slow if the array has many elements in it,
more than 100.

What is JavaScript code to perform a linear search?

Example 13
// If key is in list, returns the first index where key is located within list; otherwise
returns -1.
function linearSearch(list, key) {
for (let i=0; i<list.length; i++) {
if (list[i]== key) {
return i;
}
return -1;
}

10.10 Parallel Arrays


What are parallel arrays?
They are two or more arrays that contain corresponding values.

Student ID Student Name


07-153-4276 Felix
34-513-3186 Jonathan
26-430-0198 Grace

let studentIDs = ['07-153-4276', '34-513-3186', '26-430-0198'];


let studentNames = ['Felix', 'Jonathan', 'Grace'];

What is the JavaScript program that reads a student ID from a text field and finds
and outputs the corresponding student name, using two parallel array?

Example 14

<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Student ID to Name</title>

<script>
// The values in these parallel arrays can be hard coded into a program, or even
better, they can be read from a file of database
let studentIDs= ["07-153-4276", "34-513-3186", "26-430-0198"];
let studentNames= ["Felix", "Jonathan", "Grace"];

/* Input: a student's ID
*Processing: find the student'name
* Output: the student's name
*/
function findName() {
// Get the student's ID.
let studID=document.getElementById("stuID").value;
//Use linear search to find the student's ID.
let index= linearSearch(studentIDs, stuID);

let name;
if(index==-1) {
//The student ID that the user entered is not stored in the studentIDs array.
name = "No such student ID";
}
else {
//Get the student's name.
name= studentNames[index];

}
// Display the student´s name for the user to see.
document.getElementById("output").innerHTML= name;
}
// If key is in list, returns the first index where key is located within list;
otherwise returns -1.
function linearSearch(list, key) {
let index=-1;
for (let i=0; i<list.legth;i++) {
if (list[i]==key) {
index= i;
break;
}
}
return index;
}
</script>
</head>
<body>
Student ID: <input type="text" id="stuID" ><br>
<button type= "button" onclick="findName()">Name</button>
<div id="output"></div>
</body>
</html>
10.11 Finding a Range

What are some examples of finding the range that contains some value from a list of
numerical ranges?

Determining a person’s income tax rate from a list of income ranges and graduated tax
rates
Determining a customer’s discount rate from a list of purchase ranges and discount
rates.
Determining a salesperson’s commission form a list of sales ranges and commission
rates.
Determining a student’s letter grade from a list of score ranges and letter grades.

What is the conventional code to select a range from a list of ranges?


Example 15
// Computes and returns a discounted purchase amount.

function getDiscountedAmount(purchase){
let rate;
if (purchase<300){
rate=0;
}
else if (purchase<600) {
rate=0.02;
}
else if (purchase<1000) {
rate=0.025;
}
else {
rate=0.03;
}
let discount= purchase*rate;
return purchase-discount;
}

What is the code to select a range from a list of ranges using arrays?

// The values in these parallel arrays can be hard coded into program, or even better,
they can be read from a file or database.

let limits = [300, 600, 1000];


let rates = [0, 0.02, 0.025, 0.03];

//Computes and returns a discounted purchase amount.


function getDiscountedAmount(purchase) {
// Find the purchase range.
for (let i=0; i<limits.length; i++) {
if (purchase<limits[i]) {
break;
}
}

// Get the discount rate that corresponds to the purchase range.


let rate= rates [i];

//Compute the discount amount and discounted price.

let discount= purchase*rate;


return purchase-discount;
}
What is the program to select a range from a list of ranges?

<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Student ID to Name</title>

<script>
// The values in these parallel arrays can be hard coded into a program, or even
better, they can be read from a file of database
/* Input: The subtotal for a customer's purchases
*Processing: Compute a discounted amount and sales tax and add them
together to get the total amount that the customer owes.
* Output: The total that the customer owes
*/
function computeTotal() {
// Get the subtotal from the user.
let subtotal= parseFloat(document.getElementById("subtotal").value);
//Compute the customer's total.
let discounted= getDiscountedAmount(subtotal);
let tax= getSalesTax(discounted);
let total = discounted + tax;

//Display the total for the customer to see.


document.getElementById("total").innerHTML=total;
}
// The values in these parallel arrays can be hard coded into your program, or
even better, they can be read from a file or databes.
let limits= [300, 600, 1000];
let rates= [0, 0.02, 0.025, 0.03];
// Computes and returns a discounted purchase amount.
function getDiscountedAmount(purchase){
//Find the purchase range
for (let i=0; i<limits.length; i++) {
if (purchase <limits[i]){
break;
}
}
//Get the discount rate that corresponds to the purchase range.
let rate=rates[i];

//Compute the discount amount and round it to pennies.


let discount= purchase*rate;
discount=roundToPlaces(discount, 2);

//Compute and return the discounted price.


return purchase-discount;
}
// Computes and returns the sales tax for a purchase amount.
function getSalesTax(purchase){
let taxRate=0.06;
let tax=purchase*taxRate;
tax=roundToPlaces(tax,2);
return tax;
}

//Rounds x to digits places after the decimal.


function roundToPlaces(x, digits){
let multiplier= Math.pow(10, digits);
let rounded= Math.round(x*multiplier)/multiplier;
return rounded;
}

</script>
</head>
<body>
<h2>Compute Total</h2>
Subtotal <input type="text" id="subtotal" size="5"><br>
<button type= "button" onclick="computeTotal()">Total</button>
<div id="total"></div>
</body>
</html>

10.12 Finding a Value (Binary Search)

What is a binary search?


It is a faster algorithm to find an element within an array when the elements are
sorted.
How does this algorithm work?
It works by comparing the key with the most middle element (MME), if both are the
same, then the search is done, if not and the key is greater than the MME the
algorithm searches the key in the last half of the array. If the key is less than the MME
the algorithm searches in the first half of the array. If the key is not founded it is return
-1.

What is the code to find a value by binary search?


Example 18

//If key is in list, returns any index where key is located within list; otherwise returns
-insertPoint- 1.
// Assumes list is already sorted.

function binarySearch(list, key) {


let left=0;
let right = list.length-1;
while (left<=right) {
// Compute the index of the middle of the current interval.
let mid= left + ((right-left)>>>1);
// Compare the value in the middle of the interval to the key.
let cmp= key – list[mid];
if (cmp>0) {
left = mid +1;
}
else if (cmp<0) {
right = mid-1;
}
else {
return mid;
}
}
// key is not present in list, but if it were, it would be stored at location left.
return –(left+1);
}

10.13 Array methods


Template

arrayName.methodName(arg1, arg2, …argN);

Array methods
Method Description
a.concat(item1, item2,…) Returns a new array composed of the
original array and the argument arrays or
values
a.every(func, thisArg) Returns true if a test function returns
true for every element in an array.
a.filter(func, thisArg) Returns a new array that contains all
elements that passed a test function
a.forEach(func, thisArg) Calls a fucntin once for each element in
an array.
a.indexOf(toFind, start) Returns the index within the array a of
the first occurrence of the element
toFind, or -1 if not found.
a.join(separator) Joins all elements of an array into a
string.
a.lastIndexOf(toFind, start) Returns the index within the array a of
the last occurrence of the element
toFind, or -1 if not found.
a.map(func, thisArg) Returns a new array that contains the
results of calling a function on every
element in an array.
a.pop() Removes and returns the last element
from an array.
a.reduce(func, thisArg) Returns an accumulated value producel
by calling a function on every element in
an array.
a.reverse() Reverses the elements in an array.
a.shift() Removes and returns the first element
from an array.
a.slice(start, end) Returns a new array that is copy of
elements between [start, end).
a.some(func, thisArg) Returns true if a test function returns
true for at least one element in an array.
a.sort(compareFunc) Sorts the element of an array in place.
a.toString() Returns a string representing an array.
a.splice(start, count, item1, item2, ….) Removes and adds elements to an array.
a.unshift(item1, item2, …) Adds one or more elements to the
beginning of an array.

10.14 Sorting an array


What is the best way to sort an array?
It is using the sort functionality provided by the programing language that is being
used, the built-in sort functionality, wich is in the array object.

Example:
let vegetables = [“Radish”, “Carrot”, “Tomato”, “Pea”];
vegetables.sort();

What is the code to sort text strings in descending order?


Example 9

/* Compares two values, s1 and s2 and returns -1 if s1 should come before s2, 1 if s1
should come after s2, and 0 if the two values are equal. */

function descend (s1, s2) {


if (s1>s2)
return -1;
if (s1<s2)
return 1;
return 0;
}
let vegetables= [“Radish”, “Carrot”, “Tomato”, “Pea” ];
vegetables.sort(descend);

What are the purpose of every function in the program bellow?

<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Sort text</title>

<script>
/* Input: A list of text items, each item on a separate line.
*Processing:
* Split the text items into an array.
* Sort the array.
*Join the array into a string.
* Output: The sorted list of text items
*/
function process() {
// Get the entered by the user.
let text= document.getElementById("input").value;

// Split the text at each new line into an array of strings


let list= text.split("\n");
// Sort the array of strings:
list.sort();

// Join the sorted array into a string of text separated by newline characters.
let output= list.join("\n");
// Display the string for the user to see.
document.getElementById("output").value=output;
}
</script>
</head>
<body>
<textarea id="input" rows="16" cols="20"></textarea>
<button type= "button" onclick="process()">Sort</button>
<textarea id="output" rows="16" cols="20"></textarea>
</body>
</html>
Function Purpose
Built-in split function To split the string that the user enters
into an array
Built-in sort function To sort the array of text items
Built-in join function To join the sorted array into a string

10.15 Sorting numbers

What is the code to force JavaScript to sort an array according to its numeric values?
We have to pass a comparison function into the sort function, as is shown in the next
example.

Example 21

<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Sort text</title>

<script>
/* Input: No user input.
*Processing:Test the built-in JavaScript sort function
* Output: The contents of an array before it is sorted, and the contents after it is
sorted.
*/
function testSort() {
let numbers = [7, 10, 8, 16, 3, 35];
document.getElementById("output").innerHTML=numbers+"<br>";
numbers.sort(compareNumbers);
document.getElementById("output").innerHTML += numbers;
}
// Compares two numbers by subtracting the second from the first which will
return a negative number if the first number should be placed before the second, a
zero if the two numbers are equal, and a positive number if the first number should be
placed after the second.
function compareNumbers(x,y){
return x-y;
}

</script>
</head>
<body>
<button type= "button" onclick="testSort()">Sort an Array</button>
<div id="output"></div>
</body>
</html>

How does a sort function work?


They all work by repeatedly comparing elements in an array to other elements in the
array and simply moving the elements around within the array.

What is the JavaScript code to sort an array using the insertion sort algorithm?

Example 22

// Sorts the contents of the specified array in ascending order using the insertion sort
algorithm.

function sort(list) {
let first = 0;
let last = list.length-1;
for (let i=last-1; I >= first; i-- ) {
let swap =list[i];
for (let j=i+1; j <= last; j++){
if (swap <=list[j]) {
break;
}
list[j -1]= swap;
}
}

Common Mistakes
Forgetting that the first index in a JavaScript array is always 0

Incorrect
for (let i=1; i<a.length; i++) {
a[i] = 0;
}
Correct

for (let i=0; i<a.length; i++) {


a[i] = 0;
}
Going beyond the end of an array
Incorrect
for (let i=0; i <= a.length; i++) {
a[i] = 0;
}

Correct

for (let i=0; I < a.length; i++) {


a[i] = 0;
}
Confusing an index with the value stored at an index
Incorrect
let sum= 0;
for (let i = 0; i < a.length; i++) {
// Wrong! i is the index. This code ignores the values that are stored in the array
simply adds the indexes of the array which are the integers 0,1,2, … (a.length-1)
sum += i;
}

Correct
let sum= 0;
for (let i = 0; i < a.length; i++) {
// Right. a[i] is the value stored at index i. This code adds the values that are stored
in the ar
sum += a[i];
}
JavaScript Arrays
JavaScript arrays are used to store multiple values in a single variable.

Example
var cars = ["Saab", "Volvo", "BMW"];
What is an Array?
An array is a special variable, which can hold more than one value at a time.

If you have a list of items (a list of car names, for example), storing the cars in single
variables could look like this:

var car1 = "Saab";


var car2 = "Volvo";
var car3 = "BMW";
However, what if you want to loop through the cars and find a specific one? And what
if you had not 3 cars, but 300?

The solution is an array!

An array can hold many values under a single name, and you can access the values by
referring to an index number.

Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.

Syntax:

var array_name = [item1, item2, ...];


Example
var cars = ["Saab", "Volvo", "BMW"];
Spaces and line breaks are not important. A declaration can span multiple lines:
Example
var cars = [
"Saab",
"Volvo",
"BMW"
];

Using the JavaScript Keyword new


The following example also creates an Array, and assigns values to it:

Example
var cars = new Array("Saab", "Volvo", "BMW");
The two examples above do exactly the same. There is no need to use new Array().
For simplicity, readability and execution speed, use the first one (the array literal
method).

Access the Elements of an Array


You access an array element by referring to the index number.

This statement accesses the value of the first element in cars:

var name = cars[0];


Example
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars[0];
Note: Array indexes start with 0.

[0] is the first element. [1] is the second element.

Changing an Array Element


This statement changes the value of the first element in cars:

cars[0] = "Opel";
Example
var cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";
document.getElementById("demo").innerHTML = cars[0];
Access the Full Array
With JavaScript, the full array can be accessed by referring to the array name:

Example
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
Arrays are Objects
Arrays are a special type of objects. The typeof operator in JavaScript returns "object"
for arrays.
But, JavaScript arrays are best described as arrays.

Arrays use numbers to access its "elements". In this example, person[0] returns John:

Array:
var person = ["John", "Doe", 46];
Objects use names to access its "members". In this example, person.firstName returns
John:

Object:
var person = {firstName:"John", lastName:"Doe", age:46};
Array Elements Can Be Objects
JavaScript variables can be objects. Arrays are special kinds of objects.

Because of this, you can have variables of different types in the same Array.

You can have objects in an Array. You can have functions in an Array. You can have
arrays in an Array:

myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;
Array Properties and Methods
The real strength of JavaScript arrays are the built-in array properties and methods:

Examples
var x = cars.length; // The length property returns the number of elements
var y = cars.sort(); // The sort() method sorts arrays
Array methods are covered in the next chapters.

The length Property


The length property of an array returns the length of an array (the number of array
elements).

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length; // the length of fruits is 4
The length property is always one more than the highest array index.

Accessing the First Array Element


Example
fruits = ["Banana", "Orange", "Apple", "Mango"];
var first = fruits[0];
Accessing the Last Array Element
Example
fruits = ["Banana", "Orange", "Apple", "Mango"];
var last = fruits[fruits.length - 1];
Looping Array Elements
The safest way to loop through an array, is using a for loop:

Example
var fruits, text, fLen, i;
fruits = ["Banana", "Orange", "Apple", "Mango"];
fLen = fruits.length;

text = "<ul>";
for (i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";
You can also use the Array.forEach() function:

Example
var fruits, text;
fruits = ["Banana", "Orange", "Apple", "Mango"];

text = "<ul>";
fruits.forEach(myFunction);
text += "</ul>";

function myFunction(value) {
text += "<li>" + value + "</li>";
}
Adding Array Elements
The easiest way to add a new element to an array is using the push() method:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon"); // adds a new element (Lemon) to fruits
New element can also be added to an array using the length property:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to fruits
WARNING !
Adding elements with high indexes can create undefined "holes" in an array:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[6] = "Lemon"; // adds a new element (Lemon) to fruits
Associative Arrays
Many programming languages support arrays with named indexes.
Arrays with named indexes are called associative arrays (or hashes).

JavaScript does not support arrays with named indexes.

In JavaScript, arrays always use numbered indexes.

Example
var person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
var x = person.length; // person.length will return 3
var y = person[0]; // person[0] will return "John"
WARNING !!
If you use named indexes, JavaScript will redefine the array to a standard object.
After that, some array methods and properties will produce incorrect results.

Example:
var person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
var x = person.length; // person.length will return 0
var y = person[0]; // person[0] will return undefined
The Difference Between Arrays and Objects
In JavaScript, arrays use numbered indexes.

In JavaScript, objects use named indexes.

Arrays are a special kind of objects, with numbered indexes.

When to Use Arrays. When to use Objects.


JavaScript does not support associative arrays.
You should use objects when you want the element names to be strings (text).
You should use arrays when you want the element names to be numbers.
Avoid new Array()
There is no need to use the JavaScript's built-in array constructor new Array().

Use [] instead.

These two different statements both create a new empty array named points:

var points = new Array(); // Bad


var points = []; // Good
These two different statements both create a new array containing 6 numbers:

var points = new Array(40, 100, 1, 5, 25, 10); // Bad


var points = [40, 100, 1, 5, 25, 10]; // Good
The new keyword only complicates the code. It can also produce some unexpected
results:

var points = new Array(40, 100); // Creates an array with two elements (40 and 100)
What if I remove one of the elements?

var points = new Array(40); // Creates an array with 40 undefined elements !!!!!
How to Recognize an Array
A common question is: How do I know if a variable is an array?

The problem is that the JavaScript operator typeof returns "object":

var fruits = ["Banana", "Orange", "Apple", "Mango"];

typeof fruits; // returns object


The typeof operator returns object because a JavaScript array is an object.

Solution 1:
To solve this problem ECMAScript 5 defines a new method Array.isArray():

Array.isArray(fruits); // returns true


The problem with this solution is that ECMAScript 5 is not supported in older browsers.

Solution 2:
To solve this problem you can create your own isArray() function:

function isArray(x) {
return x.constructor.toString().indexOf("Array") > -1;
}
The function above always returns true if the argument is an array.

Or more precisely: it returns true if the object prototype contains the word "Array".

Solution 3:
The instanceof operator returns true if an object is created by a given constructor:

var fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits instanceof Array; // returns true

JavaScript Array Methods


Converting Arrays to Strings
The JavaScript method toString() converts an array to a string of (comma separated)
array values.
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
Result:

Banana,Orange,Apple,Mango
The join() method also joins all array elements into a string.

It behaves just like toString(), but in addition you can specify the separator:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");
Result:

Banana * Orange * Apple * Mango


Popping and Pushing
When you work with arrays, it is easy to remove elements and add new elements.

This is what popping and pushing is:

Popping items out of an array, or pushing items into an array.

ADVERTISEMENT

Popping
The pop() method removes the last element from an array:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop(); // Removes the last element ("Mango") from fruits
The pop() method returns the value that was "popped out":

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.pop(); // the value of x is "Mango"
Pushing
The push() method adds a new element to an array (at the end):

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi"); // Adds a new element ("Kiwi") to fruits
The push() method returns the new array length:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.push("Kiwi"); // the value of x is 5
Shifting Elements
Shifting is equivalent to popping, working on the first element instead of the last.

The shift() method removes the first array element and "shifts" all other elements to a
lower index.

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift(); // Removes the first element "Banana" from fruits
The shift() method returns the string that was "shifted out":

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.shift(); // the value of x is "Banana"
The unshift() method adds a new element to an array (at the beginning), and "unshifts"
older elements:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon"); // Adds a new element "Lemon" to fruits
The unshift() method returns the new array length.

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon"); // Returns 5
Changing Elements
Array elements are accessed using their index number:

Array indexes start with 0. [0] is the first array element, [1] is the second, [2] is the
third ...

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[0] = "Kiwi"; // Changes the first element of fruits to "Kiwi"
The length property provides an easy way to append a new element to an array:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Kiwi"; // Appends "Kiwi" to fruits
Deleting Elements
Since JavaScript arrays are objects, elements can be deleted by using the JavaScript
operator delete:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0]; // Changes the first element in fruits to undefined
Using delete may leave undefined holes in the array. Use pop() or shift() instead.

Splicing an Array
The splice() method can be used to add new items to an array:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
The first parameter (2) defines the position where new elements should be added
(spliced in).

The second parameter (0) defines how many elements should be removed.

The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added.

The splice() method returns an array with the deleted items:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 2, "Lemon", "Kiwi");
Using splice() to Remove Elements
With clever parameter setting, you can use splice() to remove elements without
leaving "holes" in the array:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0, 1); // Removes the first element of fruits
The first parameter (0) defines the position where new elements should be added
(spliced in).

The second parameter (1) defines how many elements should be removed.

The rest of the parameters are omitted. No new elements will be added.

Merging (Concatenating) Arrays


The concat() method creates a new array by merging (concatenating) existing arrays:

Example (Merging Two Arrays)


var myGirls = ["Cecilie", "Lone"];
var myBoys = ["Emil", "Tobias", "Linus"];
var myChildren = myGirls.concat(myBoys); // Concatenates (joins) myGirls and
myBoys
The concat() method does not change the existing arrays. It always returns a new
array.

The concat() method can take any number of array arguments:


Example (Merging Three Arrays)
var arr1 = ["Cecilie", "Lone"];
var arr2 = ["Emil", "Tobias", "Linus"];
var arr3 = ["Robin", "Morgan"];
var myChildren = arr1.concat(arr2, arr3); // Concatenates arr1 with arr2 and arr3
The concat() method can also take strings as arguments:

Example (Merging an Array with Values)


var arr1 = ["Emil", "Tobias", "Linus"];
var myChildren = arr1.concat("Peter");
Slicing an Array
The slice() method slices out a piece of an array into a new array.

This example slices out a part of an array starting from array element 1 ("Orange"):

Example
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1);
The slice() method creates a new array. It does not remove any elements from the
source array.

This example slices out a part of an array starting from array element 3 ("Apple"):

Example
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(3);
The slice() method can take two arguments like slice(1, 3).

The method then selects elements from the start argument, and up to (but not
including) the end argument.

Example
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1, 3);
If the end argument is omitted, like in the first examples, the slice() method slices out
the rest of the array.

Example
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(2);
Automatic toString()
JavaScript automatically converts an array to a comma separated string when a
primitive value is expected.

This is always the case when you try to output an array.


These two examples will produce the same result:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;
All JavaScript objects have a toString() method.

Finding Max and Min Values in an Array


There are no built-in functions for finding the highest or lowest value in a JavaScript
array.

You will learn how you solve this problem in the next chapter of this tutorial.

Sorting Arrays
Sorting arrays are covered in the next chapter of this tutorial.

Complete Array Reference


For a complete reference, go to our Complete JavaScript Array Reference.

The reference contains descriptions and examples of all Array properties and methods.

10.15.1 Programming Assignments


1. Write a function that creates and returns an array that
contains the values: 1908, 5, 10. The function must
have this header:
function mothersDay()

2. Write a function that returns the sum of the first and


last values in an array. The function must have this
header:
function addEnds(list)

For example, if the addEnds function were called like this:


let list = [ 17, 8, 9, 5, 20 ];
let value = addEnds(list);

the addEnds function would return 37 because 17 and 20


are the first and last values stored in the array, and the
sum of 17 and 20 is 37.

3. Write a function named getMiddle that returns the value


of the middle element in an array. If the array has an
even number of elements, then this function must
return the average of the two middle elements. The
function must have this header:
function getMiddle(list)

For example, if the getMiddle function were called like


this:
let list = [ 17, 8, 9, 5, 20 ];
let value = getMiddle(list);

the getMiddle function would return 9 because 9 is stored


in the middle of the array. If the getMiddle function were
called like this:
let list = [ 12, 4, 8, 15, 17, 5, 20, 11 ];
let value = getMiddle(list);

the getMiddle function would return 16 because 15 and 17


are stored in the middle of the array, and the average of
15 and 17 is 16.

4. Write a function named countEvens that counts and


returns the number of even integers in an array. The
function must have this header:
function countEvens(list)

For example, if the countEvens function were called like


this:
let list = [ 17, 8, 9, 5, 20 ];
let count = countEvens(list);

the countEvens function would return 2 because 8 and 20


are even integers.

5.
Write a function to multiply each element in an array by
some value and to return the products in an array. The
function must have this header:
function multiply(list, multiplier)

For example, if the multiply function were called like this:


let list = [ 17, 8, 9, 5, 20 ];
let products = multiply(list, 3);

the multiply function would return an array with these


values:
[ 51, 24, 27, 15, 60 ]

6. Write a function to rotate the elements in an array to


the left. In other words, the function must move each
element from its location to the location immediately to
the left, and then move the first value from its location
to the last location (not necessarily in that order). The
function must have this header:
function rotateLeft(list)

For example, if the rotateLeft function were called like


this:
let list = [ 17, 8, 9, 5, 20 ];
rotateLeft(list);

The rotateLeft function would change the list array to


be [ 8, 9, 5, 20, 17 ].

7. Write a function to rotate the elements in an array to


the right. In other words, the function must move each
element from its location to the location immediately to
the right, and then move the last value from its location
to the first location (not necessarily in that order). The
function must have this header:
function rotateRight(list)

For example, if the rotateRight function were called like


this:
let list = [ 17, 8, 9, 5, 20 ];
rotateRight(list);
The rotateRight function would change the list array to
be [ 20, 17, 8, 9, 5 ].

8. In the card game named golf, each player tries to


collect cards with the lowest value. The game is usually
played with a deck of cards that has four suits: spades,
hearts, diamonds, and clubs. Each suit has 13 cards: 1,
2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, and King. At the
end of the game, each player calculates his score by
adding the value of the cards that he holds in his hand.
The value of the numbered cards is the same as their
number. However, the value of a Jack, Queen, or King
is 10. In some versions of the game, each player has
four cards in his hand. In other versions each player
has six or eight cards in his hand.

Write a function named golfScore that takes one


parameter: an array named hand. This function must
compute and return the score for the cards by adding
the values of all the cards in hand. For example,
if hand were this array: [5, 2, "King", 3, 1, "Queen"],
the golfScore function would return 31.

9. 183

Write an HTML document with a button and a div.


The onclick attribute of the button must call a function
named crazyStory() with no arguments. The div must
have an id of 'output'. Write these five functions in the
head of the document, all in the same script tag:
function chooseNoun()
function chooseVerb()
function chooseAdjective()
function chooseAdverb()
function chooseInteger()

The first four functions must each contain an array with


at least ten words. The chooseNoun function must contain
an array with at least ten nouns. The chooseVerb function
must contain an array with at least ten verbs, and so on.
When one of these four functions is called, the function
must randomly choose one of the words in its array and
return that word. Hint: write code similar
to example 8 of Chapter 9 to get a pseudo random index
between 0 and the length of the array of words, in other
words in this range [0, length). Then write code to
return the word that is stored in the array at that index.

The last function, chooseInteger must return a pseudo


random integer between 1 and 99, inclusive. Finally add
this function to the same script tag as the other five
functions.
function crazyStory() {
let story = "The man comes "
+ chooseVerb() + "ing a horse. The horse is "
+ chooseAdverb() + " " + chooseAdjective()
+ " and has no " + chooseNoun()
+ ". The saddle is " + chooseAdjective()
+ ", and the stirrups don't match. His clothing"
+ " is strange. He wears " + chooseInteger()
+ " hats and a " + chooseAdjective()
+ " shirt. One " + chooseNoun()
+ " of his pants is torn off to the knee. His sword is "
+ chooseAdjective() + " and has a broken hilt and "
+ chooseVerb() + "s from the bottom of the "
+ chooseNoun() + ".";
document.getElementById('output').innerHTML = story;
}

10. 184

The Twelve Days of Christmas is an English Christmas


carol that lists a series of gifts given on each of the
twelve days of Christmas. In the song, the gifts are
listed cumulatively. This means on day one, the song
lists the gift for day one. On day two, the song lists the
gifts for day two and day one. On day three, the song
lists the gifts for days three, two, and one and so on.
These are the gifts for each of the twelve days:

Day Gift
1 a partridge in a pear tree
2 two turtle doves
3 three French hens
4 four calling birds
5 five golden rings
6 six geese a laying
7 seven swans a swimming
8 eight maids a milking
9 nine ladies dancing
10 ten lords a leaping
11 eleven pipers piping
Day Gift
12 twelve drummers drumming

Write a program that allows a user to enter an integer


between 1 and 12, inclusive and that displays the
corresponding lyrics from The Twelve Days of Christmas.
For example, if a user entered 1, your program should
output:

“On the first day of Christmas, my true love gave to me:


a partridge in a pear tree.”

If the user entered 4, your program should output:

“On the fourth day of Christmas, my true love gave to


me: four calling birds, three French hens, two turtle
doves, and a partridge in a pear tree.”

Hint: create an array that contains the ordinal numbers:


first, second, third… and another array that contains the
gifts. Use those arrays, a loop, and string concatenation
to build a string that contains the lyrics.

11. 185

Write an HTML document with two text areas and a


button. Write a JavaScript program that will

1. read all the text from the first text area,

2. split the text into numbers in an array,

3. sort the array numerically, and

4. display the sorted numbers in the second text area.

12.

Write a JavaScript program that allows a user to enter a


list of names in a text area. When the user clicks a
button, the program should output the list of names
without any duplicated names. In other words, the
program should output each name once only. Hint: The
program should read the names from the left text area
and store them in an array. Then it should sort the
array, remove the duplicate names from the array, and
display the names in the right text area.

13. 186

Here is an array that holds a representation of all the


cards in a deck Rook cards.
let cards = [
"Green 1", "Green 2", "Green 3", "Green 4", "Green 5",
"Green 6", "Green 7", "Green 8", "Green 9", "Green 10",
"Green 11", "Green 12", "Green 13", "Green 14",
"Yellow 1", "Yellow 2", "Yellow 3", "Yellow 4", "Yellow 5",
"Yellow 6", "Yellow 7", "Yellow 8", "Yellow 9", "Yellow 10",
"Yellow 11", "Yellow 12", "Yellow 13", "Yellow 14",
"Black 1", "Black 2", "Black 3", "Black 4", "Black 5",
"Black 6", "Black 7", "Black 8", "Black 9", "Black 10",
"Black 11", "Black 12", "Black 13", "Black 14",
"Red 1", "Red 2", "Red 3", "Red 4", "Red 5",
"Red 6", "Red 7", "Red 8", "Red 9", "Red 10",
"Red 11", "Red 12", "Red 13", "Red 14", "Rook Bird"
];

Read about the Fisher-Yates shuffle algorithm at


wikipedia.org. Then write a JavaScript program that will
shuffle the strings in the cards array and display the
shuffled cards in a text area. Hint: find the “modern
algorithm” that is shown about one fourth of the way
down in the Wikipedia article. Translate this “modern
algorithm” into JavaScript code.

14. Write a function that uses an array and


no if statements to solve the Arabic number to Roman
numerals programming assignment as given in
chapter 6.

Write a JavaScript function named averageBig with this header


function averageBig(list) {

The parameter list is an array that contains numbers. The length of


the list array will vary. Your function must compute the average of
all the numbers stored in the array that are larger than 1000. For
example, if your function were called like this:

var list = [70, 1010, 950, 2014, 6];


var score = averageBig(list);

your function would return the number 1512. If none of the numbers
in the array are larger than 1000, your function must return 0 (zero).

Test Cases
Parameter
list Return
[ 70, 1010, 950, 2014, 6 ] 1512
[ -72.3, 3000, 873, 2312, 68, 7501.3 ] 4271.1
[ 70, 950, 671, 6 ] 0

indeed.com, monster.com, glassdoor.com, linkedin.com,


careerbuilder.com

You might also like