PROGRAMMING WITH JavaScript Introduction
PROGRAMMING WITH JavaScript Introduction
INTRODUCTION TO
PROGRAMMING
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
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 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.
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
What is an algorithm?
It is a list of steps to perform a task.
2.2 ALGORITHMS
How many control structures are there and what are they?
A text editor like Visual studio Code VS Code, brackets Brackets or sublime
Sublime and a browser
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-->
Attr. name
Attr. value
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.
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
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>
<!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
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?
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.
function showMessage(){
//The next line of code causes the computer to open a popup window that
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
delicious!" */
4.3 STATEMENTS
What is a statement and how does it end?
function showMessage(){
//The next line of code causes the computer to open a popup window that
alert("Water is delicious");
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
<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?
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.
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.
JavaScript Types
Array Boolean Date Function
Math Number Object RegExp
String
JavaScript Objects
document event window
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.
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
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
7. What is the attribute of a button that contains JavaScript code that will be
8. Write the opening HTML tag that makes a div that can be used by this
JavaScript statement:
Include the surrounding less than (<) and greater than (>) symbols and necessary
JACASRIPT W3SCHOOL
INTRODUCTION
document.getElementById("demo").innerHTML = "Hello JavaScript";
<!DOCTYPE html>
<html>
<body>
</body>
</html>
an <img> tag:
<!DOCTYPE html>
<html>
<body>
<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>
</body>
</html>
Example
document.getElementById("demo").style.fontSize = "35px";
<!DOCTYPE html>
<html>
<body>
<button type="button"
onclick="document.getElementById('demo').style.fontSize='35px'">Click Me!</button>
</body>
</html>
Example
document.getElementById("demo").style.display = "none";
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Example
document.getElementById("demo").style.display = "block"
<!DOCTYPE html>
<html>
<body>
<button type="button"
onclick="document.getElementById('demo').style.display='block'">Click Me!</button>
</body>
</html>
JAVASCRIPT WHERE TO
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 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>
<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>
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
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>
<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>
<script>
document.write(5 + 6);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script>
document.write(5 + 6);
</script>
</body>
</html>
Example
<!DOCTYPE html>
<html>
<body>
</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>
<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>
</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 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 id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello Dolly.";
</script>
</body>
</html>
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>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<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.
<!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>
<h2>JavaScript Statements</h2>
<p>JavaScript code blocks are written between { and }</p>
<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>
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
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
window
Here is a list of some of the keywords you will learn about in this tutorial:
Keyword Description
debugger Stops the execution of JavaScript, and calls (if available) the
debugging function
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 id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 10.50;
</script>
</body>
</html>
'John Doe'
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Strings</h2>
<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 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>
<script>
document.getElementById("demo").innerHTML = (5 + 6) * 10;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<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>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Expressions</h2>
<p id="demo"></p>
<script>
var x;
x = 5;
document.getElementById("demo").innerHTML = x * 10;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Expressions</h2>
<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>
<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>
<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.
<!DOCTYPE html>
<html>
<body>
<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 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.
// 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.";
<!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>
</body>
</html>
<!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.
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;
document.write(userName);
document.write ("<br/>");
document.write(userBattingAverage);
document.write ("<br/>");
document.write("Age in dog years:" + ageInDogYears)
</script>
</body>
</html>
<!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;
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”
Example:
let swap = a;
a= b;
b=swap;
5.9 MODULUS
What does modulus operator return?
The remainder operator returns the signed remainder (+ or -) of a division.
Examples:
7%3= 1
12%3=0
-6%4=-2
6%-4=2
-6%-4-= -2
How does computer evaluate an expression with two or more operators with the same
precedence?
9
f = c+32
5
<!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);
<body>
Enter a temperature in Celsius: <input type="text"
id="celsiusInputBox">
<button type="button"
onclick="celsToFahr()">Convert</button>
<div id="fahrenDiv"></div>
</body>
</html>
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.
Examples:
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:
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?
b= 17
let a= 4;
let b= ++ a * 3 + 2;
b= 14
let q=7;
let s= 2 + 18 / --q;
s=5
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)
REVIEW QUESTIONS
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 »
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
++ Increment
-- Decrement
Arithmetic operators are fully described in the JS Arithmetic chapter.
= 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.
== equal to
!= not equal
|| logical or
! logical not
Logical operators are fully described in the JS Comparisons chapter.
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.
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 »
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
Rounding results in assigments and to write down in notebook how to round results.
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 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?
−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.
<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);
W3schools
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;
7.4 Exclusive Or
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:
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
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
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
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)) {
None
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));
if (x != 4 && y >= 0)
if (x != 4 || y > 0)
if (x == 4 && y < 0)
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.
let i= 1;
while (i<=3) {
alert(''leaf'');
i++;
}
DESCENDS:
for (let i=3; i>=1; i--) {
alert(''caterpillar'');
}
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
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.
<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>
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
// or
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;
}
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"?
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"?
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
What part of the loop must not be forgotten in order to avoid infinite loop?
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?
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 is a parameter?
It is a variable whose value comes from outside the function.
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.
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.
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) {
What about the order of parameters in a function and arguments to call a function?
They must be on the same place.
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);
What is the code to call a function and assign its result to a variable so that the result
can be used later?
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 testCalories(){
let dist=2000;
let elev = 750;
let weight = 72.6;
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);
document.getElementById('outputDiv').innerHTML = r;
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:
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
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.
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
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.
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)
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
function doInputOutput()
function houseVolume(width, depth, height, sweep)
function livingVolume(width, depth, height)
function roofVolume(width, depth, sweep)
function triangleArea(a, b, c)
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 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 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?
Example
let attempts;
function squareArea(length) {
let area=length*length;
return area;
}
Variable Scope
attempts Global
length function
width function
area Block
function randomInteger() {
let min =5;
let max=11;
<!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;
}
Function highlighted with red get the input user, call the function isEven and display
the output to the user.
<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;
}
b2 2
e=
√2
+h
e : edge length of the pyramid
SAS= √ s( s−e)( s−b)(s−e)
<!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;
}
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;
}
</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?
<!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;
}
</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)
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 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)
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)
function doPayment()
function doBalance()
function computePayment(principal, annualRate, years, periodsPerYear)
function computeBalance(principal, annualRate, years, periodsPerYear,
numberOfPaymentsPaidToDate)
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.
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.
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.
Example 1
let data;
let scores;
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]
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;
arrayName[index]
Example 7
Example 8
let list = new Array(80);
fill(list, 7);
function fill(list, x) {
// For each index in the array named list,
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;
}
}
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
Example 11
function reverse(list) {
let left=0;
let right = list.length-1;
while (left<right) {
Example 12
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)
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;
}
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.
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.
<!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;
</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>
//If key is in list, returns any index where key is located within list; otherwise returns
-insertPoint- 1.
// Assumes list is already sorted.
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.
Example:
let vegetables = [“Radish”, “Carrot”, “Tomato”, “Pea”];
vegetables.sort();
/* 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. */
<!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;
// 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
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>
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
Correct
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:
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:
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).
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.
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.
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).
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.
Use [] instead.
These two different statements both create a new empty array named points:
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?
Solution 1:
To solve this problem ECMAScript 5 defines a new method Array.isArray():
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:
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:
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.
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.
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.
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.
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.
The reference contains descriptions and examples of all Array properties and methods.
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)
9. 183
10. 184
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
11. 185
12.
13. 186
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