SlideShare a Scribd company logo
JavaScript Basics
Jerry Cain
CS 106AX
September 25, 2024
slides leveraged from those written by Eric Roberts
Control Statements
Statement Types in JavaScript
• Statements in JavaScript fall into three basic types:
– Simple statements
– Compound statements
– Control statements
• Simple statements are typically assignments, function calls, or
applications of the ++ or -- operators. Simple statements are
always terminated with a semicolon.
• Compound statements (also called blocks) are sequences of
statements enclosed in curly braces.
• Control statements fall into two categories:
– Conditional statements that require some test be evaluated
– Iterative statements that specify repetition
Boolean Expressions
• JavaScript defines two types of operators that work with
Boolean data: relational operators and logical operators.
• There are six relational operators that compare values of other
types and produce a true/false result:
=== Equals
< Less than
!== Not equals
<= Less than or equal to
>= Greater than or equal to
> Greater than
For example, the expression n <= 10 has the value true if n is
less than or equal to 10 and the value false otherwise.
p || q means either p or q (or both)
• There are also three logical operators:
&& Logical AND
|| Logical OR
! Logical NOT
p && q means both p and q
!p means the opposite of p
Notes on the Boolean Operators
• Remember that JavaScript uses = for assignment. To test
whether two values are equal, you must use the === operator.
• The || operator means either or both, which is not always
clear in the English interpretation of or.
• It is not legal in JavaScript to use more than one relational
operator in a single comparison. To express the idea
embodied in the mathematical expression
0 ≤ x ≤ 9
0 <= x && x <= 9
you need to make both comparisons explicit, as in
• Be careful when you combine the ! operator with && and ||
because the interpretation often differs from informal English.
Short-Circuit Evaluation
• JavaScript evaluates the && and || operators using a strategy
called short-circuit mode in which it evaluates the right
operand only if it needs to do so.
• One of the advantages of short-circuit evaluation is that you
can use && and || to prevent errors. If n were 0 in the earlier
example, evaluating x % n would result in a division by zero.
• For example, if n is 0, the right operand of && in
n !== 0 && x % n === 0
is not evaluated at all because n !== 0 is false. Because the
expression
false && anything
is always false, the rest of the expression no longer matters.
The if Statement
if (condition) {
statements to be executed if the condition is true
}
• The simplest of the control statements is the if statement,
which occurs in two forms. You use the first when you need
to perform an operation only if a particular condition is true:
if (condition) {
statements to be executed if the condition is true
} else {
statements to be executed if the condition is false
}
• You use the second form whenever you need to choose
between two alternative paths, depending on whether the
condition is true or false:
Functions Involving Control Statements
• The body of a function can contain statements of any type,
including control statements. As an example, the following
function uses an if statement to find the larger of two values:
function max(x, y) {
if (x > y) {
return x;
} else {
return y;
}
}
• As this example makes clear, return statements can be used
at any point in the function and may appear more than once.
The switch Statement
The switch statement provides a convenient syntax for choosing
among a set of possible paths:
switch ( expression ) {
case v1:
statements to be executed if expression = v1
break;
case v2:
statements to be executed if expression = v2
break;
. . . more case clauses if needed . . .
default:
statements to be executed if no values match
break;
}
switch ( expression ) {
case v1:
statements to be executed if expression is equal to v1
break;
case v2:
statements to be executed if expression is equal to v2
break;
. . . more case clauses if needed . . .
default:
statements to be executed if no values match
break;
}
JavaScript evaluates statements in the case or default clause
until it reaches a break or a return statement.
If none of the values in the case clauses match the expression,
JavaScript evaluates the statements in the default clause.
JavaScript then looks for a case clause that matches expression.
If expression is equal to v2, JavaScript chooses the second clause.
When JavaScript executes a switch statement, it begins by
evaluating expression.
The switch statement provides a convenient syntax for choosing
among a set of possible paths:
Example of the switch Statement
function monthName(month) {
switch (month) {
case 1: return "January";
case 2: return "February";
case 3: return "March";
case 4: return "April";
case 5: return "May";
case 6: return "June";
case 7: return "July";
case 8: return "August";
case 9: return "September";
case 10: return "October";
case 11: return "November";
case 12: return "December";
default: return undefined;
}
}
The switch statement is useful when a function must choose
among several cases, as in the following example:
The while Statement
while ( condition ) {
statements to be repeated
}
while ( condition ) {
statements to be repeated
}
• The while statement is the simplest of JavaScript’s iterative
control statements and has the following form:
• When JavaScript encounters a while statement, it begins by
evaluating the condition in parentheses.
• If the value of condition is true, JavaScript executes the
statements in the body of the loop.
• At the end of each cycle, JavaScript reevaluates condition to
see whether its value has changed. If condition evaluates to
false, JavaScript exits from the loop and continues with the
statement following the end of the while body.
The digitSum Function
n result
1729
n sum
1729 0
9
172 11
17 18
1 19
0
19
digitSum(1729) = 19
The for Statement
for ( init ; test ; step ) {
statements to be repeated
}
Evaluate init, which typically declares a control variable.
1.
Evaluate test and exit from the loop if the value is false.
2.
Execute the statements in the body of the loop.
3.
Evaluate step, which usually updates the control variable.
4.
Return to step 2 to begin the next loop cycle.
5.
for ( init ; test ; step ) {
statements to be repeated
}
• The for statement in JavaScript is a powerful tool for
specifying the structure of a loop independently from the
operations the loop performs. The syntax looks like this:
• JavaScript evaluates a for statement as follows:
Exercise: Reading for Statements
Describe the effect of each of the following for statements:
This statement executes the loop body ten times, with the control
variable i taking on each successive value between 1 and 10.
for (let i = 1; i <= 10; i++)
1.
This statement executes the loop body n times, with i counting from
0 to n-1. This version is the standard Repeat-n-Times idiom.
for (let i = 0; i < n; i++)
2.
This statement counts backward from 99 to 1 by twos.
for (let n = 99; n >= 1; n -= 2)
3.
This statement executes the loop body with the variable x taking on
successive powers of two from 1 up to 1024.
for (let x = 1; x <= 1024; x *= 2)
4.
The factorial Function
• The factorial of a number n (which is usually written as n! in
mathematics) is defined to be the product of the integers from
1 up to n. Thus, 5! is equal to 120, which is 1x 2x 3x 4x 5.
function fact(n) {
let result = 1;
for (let i = 1; i <= n; i++) {
result = result * i;
}
return result;
}
• The following function definition uses a for loop to compute
the factorial function:
The factorialTable Function
-> factorialTable(0, 7);
min max i
0 7 0
n result i
0 1 1
1
0! = 1
1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
6
7
n result i
7 1 1
1 2
2 3
6 4
24 5
120 6
720 7
5040 8
5040
7! = 5040
8
->
Comparing for and while
for ( init ; test ; step ) {
statements to be repeated
}
init;
while ( test ) {
statements to be repeated
step;
}
• The for statement
is functionally equivalent to the following code using while:
• The advantage of the for statement is that everything you
need to know to understand how many times the loop will run
is explicitly included in the header line.
Functions Mechanics
A Quick Review of Functions
• The concept of a function should be familiar to you from prior
programming experience. All modern programming
languages allow functions to be defined.
• At the most basic level, a function is a sequence of statements
that has been collected together and given a name. The name
makes it possible to execute the statements much more easily;
instead of copying out the entire list of statements, you can
just provide the function name.
• The following terms are useful when working with functions:
– Invoking a function by name is known as calling that function.
– The caller passes information to a function using arguments.
– When a function completes its operation, it returns to its caller.
– A function gives information to the caller by returning a result.
Review: Syntax of Functions
• The general form of a function definition is
function name(parameter list) {
statements in the function body
}
where name is the name of the function, and parameter list is
a list of variables used to hold the values of each argument.
• You can return a value from a function by including one or
more return statements, which are usually written as
return expression;
where expression is an expression that specifies the value you
want to return.
Nonnumeric Functions
• Although functions return a single value, that value can be of
any type.
• Even without learning the full range of string operations
covered in Chapter 7, you can already write string functions
that depend only on concatenation, such as the following
function that concatenates together n copies of the string str:
function concatNCopies(n, str) {
let result = "";
for (let i = 0; i < n; i++) {
result += str;
}
return result;
}
Exercise: Console Pyramid
• Write a program that uses the concatNCopies function to
display a pyramid on the console in which the bricks are
represented by the letter x. The number of levels in the
pyramid should be defined as the constant N_LEVELS.
• For example, if N_LEVELS is 10, the console output should
look like this:
ConsolePyramid
x
xxx
xxxxx
xxxxxxx
xxxxxxxxx
xxxxxxxxxxx
xxxxxxxxxxxxx
xxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxx
Predicate Functions
• Functions that return Boolean values play a central role in
programming and are called predicate functions. As an
example, the following function returns true if the first
argument is divisible by the second, and false otherwise:
function isDivisibleBy(x, y) {
return x % y === 0;
}
• Once you have defined a predicate function, you can use it
any conditional expression. For example, you can print the
integers between 1 and 100 that are divisible by 7 as follows:
for (let i = 1; i <= 100; i++) {
if (isDivisibleBy(i, 7)) {
println(i);
}
}
Using Predicate Functions Effectively
• New programmers often seem uncomfortable with Boolean
values and end up writing ungainly code. For example, a
beginner might write isDivisibleBy like this:
function isDivisibleBy(x, y) {
if (x % y === 0) {
return true;
} else {
return false;
}
}
• A similar problem occurs when novices explicitly check to
see whether a predicate function returns true. You should be
careful to avoid such redundant tests in your own programs.
While this code is technically correct, it is inelegant and
should be replaced by return x % y === 0.
The Purpose of Parameters
• In general, functions perform some service to their callers. In
order to do so, the function needs to know any details
required to carry out the requested task.
• Imagine that you were working as a low-level animator at
Disney Studies in the days before computerized animation
and that one of the senior designers asked you to draw a filled
circle. What would you need to know?
• At a minimum, you would need to know where the circle
should be placed in the frame, how big to make it, and what
color it should be. Those values are precisely the information
conveyed in the parameters.
“All right, Mr. Wiseguy,” she said, “you’re so clever,
you tell us what color it should be.”
Douglas Adams, The Restaurant
at the End of the Universe, 1980
—
Libraries
• To make programming easier, all modern languages include
collections of predefined functions. Those collections are
called libraries.
• For programming that involves mathematical calculations, the
most useful library is the Math library, which includes a
number of functions that will be familiar from high-school
mathematics (along with many that probably aren’t). A list of
the most important functions appears on the next slide.
• In JavaScript, each of the functions in the Math library begins
with the library name followed by a dot and then the name of
the function. For example, the function that calculates square
roots is named Math.sqrt.
• You call library functions just like any other function, so that
calling Math.sqrt(16) returns the value 4.
Useful Functions in the Math Library
Math.abs(x)
Math.max(x, y, . . .)
Math.min(x, y, . . .)
Math.round(x)
Math.floor(x)
Math.log(x)
Math.pow(x, y)
Math.sin(q )
Math.cos(q )
Math.sqrt(x)
Math.PI
Math.E
Math.exp(x)
The mathematical constant π
The mathematical constant e
The absolute value of x
The largest of the arguments
The smallest of the arguments
The closest integer to x
The largest integer not exceeding x
The natural logarithm of x
The inverse logarithm (ex)
The value x raised to the y power (xy)
The sine of q, measured in radians
The cosine of q, measured in radians
The square root of x
Math.random() A random value between 0 and 1
Decomposition
Decomposition
• The most effective way to solve a complex problem is to
break it down into successively simpler subproblems.
• You start by breaking the whole task down into simpler parts.
• Some of those tasks may themselves need subdivision.
• This process is called stepwise refinement or decomposition.
Complete Task
Subtask #1 Subtask #2 Subtask #3
Subsubtask #2a Subsubtask #2b
Criteria for Choosing a Decomposition
The proposed steps should be easy to explain. One
indication that you have succeeded is being able to find
simple names.
1.
The steps should be as general as possible. Programming
tools get reused all the time. If your methods perform
general tasks, they are much easier to reuse.
2.
The steps should make sense at the level of abstraction at
which they are used. If you have a method that does the
right job but whose name doesn’t make sense in the context
of the problem, it is probably worth defining a new method
that calls the old one.
3.
Exercise: Ruth-Aaron Pairs
• Write a program that lists the first NUM_PAIRS Ruth-Aaron
pairs. In recreational mathematics, a Ruth-Aaron pair
consists of two neighboring integers—e.g. 714 and 715—for
which the sum of the distinct prime factors of each are equal.
• The pairs are named Ruth-Aaron as a nod to baseball greats
Babe Ruth and Hank Aaron. Ruth held the record for most
career home runs at 714 until
Aaron’s hit his 715th on
April 8th, 1974.
• If NUM_PAIRS equals 15, the
program should publish the
output presented on the right.
The End

More Related Content

Similar to Java Script Basics presentation of program (20)

Unit - 4 all script are here Javascript.pptx
Unit - 4 all script are here Javascript.pptxUnit - 4 all script are here Javascript.pptx
Unit - 4 all script are here Javascript.pptx
kushwahanitesh592
 
DIWE - Programming with JavaScript
DIWE - Programming with JavaScriptDIWE - Programming with JavaScript
DIWE - Programming with JavaScript
Rasan Samarasinghe
 
javascriptbasicsPresentationsforDevelopers
javascriptbasicsPresentationsforDevelopersjavascriptbasicsPresentationsforDevelopers
javascriptbasicsPresentationsforDevelopers
Ganesh Bhosale
 
control_javascript_for _beginners_and _pro.pptx
control_javascript_for _beginners_and _pro.pptxcontrol_javascript_for _beginners_and _pro.pptx
control_javascript_for _beginners_and _pro.pptx
vivekkn69
 
Javascript
JavascriptJavascript
Javascript
vikram singh
 
Javascript - Tutorial
Javascript - TutorialJavascript - Tutorial
Javascript - Tutorial
adelaticleanu
 
Les origines de Javascript
Les origines de JavascriptLes origines de Javascript
Les origines de Javascript
Bernard Loire
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
Raghavan Mohan
 
The Java Script Programming Language
The  Java Script  Programming  LanguageThe  Java Script  Programming  Language
The Java Script Programming Language
zone
 
Javascript
JavascriptJavascript
Javascript
guest03a6e6
 
Javascript by Yahoo
Javascript by YahooJavascript by Yahoo
Javascript by Yahoo
birbal
 
Loops and iteration.docx
Loops and iteration.docxLoops and iteration.docx
Loops and iteration.docx
NkurikiyimanaGodefre
 
Javascript
JavascriptJavascript
Javascript
vikram singh
 
03. Week 03.pptx
03. Week 03.pptx03. Week 03.pptx
03. Week 03.pptx
Vinc2ntCabrera
 
Javascript
JavascriptJavascript
Javascript
Gita Kriz
 
Class[2][29th may] [javascript]
Class[2][29th may] [javascript]Class[2][29th may] [javascript]
Class[2][29th may] [javascript]
Saajid Akram
 
CS101- Introduction to Computing- Lecture 23
CS101- Introduction to Computing- Lecture 23CS101- Introduction to Computing- Lecture 23
CS101- Introduction to Computing- Lecture 23
Bilal Ahmed
 
Fewd week5 slides
Fewd week5 slidesFewd week5 slides
Fewd week5 slides
William Myers
 
JAVASCRIPT - LinkedIn
JAVASCRIPT - LinkedInJAVASCRIPT - LinkedIn
JAVASCRIPT - LinkedIn
Gino Louie Peña, ITIL®,MOS®
 
FFW Gabrovo PMG - JavaScript 1
FFW Gabrovo PMG - JavaScript 1FFW Gabrovo PMG - JavaScript 1
FFW Gabrovo PMG - JavaScript 1
Toni Kolev
 
Unit - 4 all script are here Javascript.pptx
Unit - 4 all script are here Javascript.pptxUnit - 4 all script are here Javascript.pptx
Unit - 4 all script are here Javascript.pptx
kushwahanitesh592
 
DIWE - Programming with JavaScript
DIWE - Programming with JavaScriptDIWE - Programming with JavaScript
DIWE - Programming with JavaScript
Rasan Samarasinghe
 
javascriptbasicsPresentationsforDevelopers
javascriptbasicsPresentationsforDevelopersjavascriptbasicsPresentationsforDevelopers
javascriptbasicsPresentationsforDevelopers
Ganesh Bhosale
 
control_javascript_for _beginners_and _pro.pptx
control_javascript_for _beginners_and _pro.pptxcontrol_javascript_for _beginners_and _pro.pptx
control_javascript_for _beginners_and _pro.pptx
vivekkn69
 
Javascript - Tutorial
Javascript - TutorialJavascript - Tutorial
Javascript - Tutorial
adelaticleanu
 
Les origines de Javascript
Les origines de JavascriptLes origines de Javascript
Les origines de Javascript
Bernard Loire
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
Raghavan Mohan
 
The Java Script Programming Language
The  Java Script  Programming  LanguageThe  Java Script  Programming  Language
The Java Script Programming Language
zone
 
Javascript by Yahoo
Javascript by YahooJavascript by Yahoo
Javascript by Yahoo
birbal
 
Class[2][29th may] [javascript]
Class[2][29th may] [javascript]Class[2][29th may] [javascript]
Class[2][29th may] [javascript]
Saajid Akram
 
CS101- Introduction to Computing- Lecture 23
CS101- Introduction to Computing- Lecture 23CS101- Introduction to Computing- Lecture 23
CS101- Introduction to Computing- Lecture 23
Bilal Ahmed
 
FFW Gabrovo PMG - JavaScript 1
FFW Gabrovo PMG - JavaScript 1FFW Gabrovo PMG - JavaScript 1
FFW Gabrovo PMG - JavaScript 1
Toni Kolev
 

Recently uploaded (20)

Hemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptxHemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptx
Arshad Shaikh
 
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Celine George
 
How to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 SlidesHow to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 Slides
Celine George
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdfFEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Strengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptxStrengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptx
SteffMusniQuiballo
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptxjune 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
Adam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational PsychologyAdam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational Psychology
Prachi Shah
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.
jmansha170
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptxCapitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Allomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdfAllomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdf
Abha Pandey
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdfUnit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
National Information Standards Organization (NISO)
 
How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18
Celine George
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
GeorgeDiamandis11
 
Hemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptxHemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptx
Arshad Shaikh
 
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Celine George
 
How to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 SlidesHow to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 Slides
Celine George
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdfFEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Strengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptxStrengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptx
SteffMusniQuiballo
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptxjune 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
Adam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational PsychologyAdam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational Psychology
Prachi Shah
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.
jmansha170
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptxCapitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Allomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdfAllomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdf
Abha Pandey
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdfUnit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18
Celine George
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
GeorgeDiamandis11
 
Ad

Java Script Basics presentation of program

  • 1. JavaScript Basics Jerry Cain CS 106AX September 25, 2024 slides leveraged from those written by Eric Roberts
  • 3. Statement Types in JavaScript • Statements in JavaScript fall into three basic types: – Simple statements – Compound statements – Control statements • Simple statements are typically assignments, function calls, or applications of the ++ or -- operators. Simple statements are always terminated with a semicolon. • Compound statements (also called blocks) are sequences of statements enclosed in curly braces. • Control statements fall into two categories: – Conditional statements that require some test be evaluated – Iterative statements that specify repetition
  • 4. Boolean Expressions • JavaScript defines two types of operators that work with Boolean data: relational operators and logical operators. • There are six relational operators that compare values of other types and produce a true/false result: === Equals < Less than !== Not equals <= Less than or equal to >= Greater than or equal to > Greater than For example, the expression n <= 10 has the value true if n is less than or equal to 10 and the value false otherwise. p || q means either p or q (or both) • There are also three logical operators: && Logical AND || Logical OR ! Logical NOT p && q means both p and q !p means the opposite of p
  • 5. Notes on the Boolean Operators • Remember that JavaScript uses = for assignment. To test whether two values are equal, you must use the === operator. • The || operator means either or both, which is not always clear in the English interpretation of or. • It is not legal in JavaScript to use more than one relational operator in a single comparison. To express the idea embodied in the mathematical expression 0 ≤ x ≤ 9 0 <= x && x <= 9 you need to make both comparisons explicit, as in • Be careful when you combine the ! operator with && and || because the interpretation often differs from informal English.
  • 6. Short-Circuit Evaluation • JavaScript evaluates the && and || operators using a strategy called short-circuit mode in which it evaluates the right operand only if it needs to do so. • One of the advantages of short-circuit evaluation is that you can use && and || to prevent errors. If n were 0 in the earlier example, evaluating x % n would result in a division by zero. • For example, if n is 0, the right operand of && in n !== 0 && x % n === 0 is not evaluated at all because n !== 0 is false. Because the expression false && anything is always false, the rest of the expression no longer matters.
  • 7. The if Statement if (condition) { statements to be executed if the condition is true } • The simplest of the control statements is the if statement, which occurs in two forms. You use the first when you need to perform an operation only if a particular condition is true: if (condition) { statements to be executed if the condition is true } else { statements to be executed if the condition is false } • You use the second form whenever you need to choose between two alternative paths, depending on whether the condition is true or false:
  • 8. Functions Involving Control Statements • The body of a function can contain statements of any type, including control statements. As an example, the following function uses an if statement to find the larger of two values: function max(x, y) { if (x > y) { return x; } else { return y; } } • As this example makes clear, return statements can be used at any point in the function and may appear more than once.
  • 9. The switch Statement The switch statement provides a convenient syntax for choosing among a set of possible paths: switch ( expression ) { case v1: statements to be executed if expression = v1 break; case v2: statements to be executed if expression = v2 break; . . . more case clauses if needed . . . default: statements to be executed if no values match break; } switch ( expression ) { case v1: statements to be executed if expression is equal to v1 break; case v2: statements to be executed if expression is equal to v2 break; . . . more case clauses if needed . . . default: statements to be executed if no values match break; } JavaScript evaluates statements in the case or default clause until it reaches a break or a return statement. If none of the values in the case clauses match the expression, JavaScript evaluates the statements in the default clause. JavaScript then looks for a case clause that matches expression. If expression is equal to v2, JavaScript chooses the second clause. When JavaScript executes a switch statement, it begins by evaluating expression. The switch statement provides a convenient syntax for choosing among a set of possible paths:
  • 10. Example of the switch Statement function monthName(month) { switch (month) { case 1: return "January"; case 2: return "February"; case 3: return "March"; case 4: return "April"; case 5: return "May"; case 6: return "June"; case 7: return "July"; case 8: return "August"; case 9: return "September"; case 10: return "October"; case 11: return "November"; case 12: return "December"; default: return undefined; } } The switch statement is useful when a function must choose among several cases, as in the following example:
  • 11. The while Statement while ( condition ) { statements to be repeated } while ( condition ) { statements to be repeated } • The while statement is the simplest of JavaScript’s iterative control statements and has the following form: • When JavaScript encounters a while statement, it begins by evaluating the condition in parentheses. • If the value of condition is true, JavaScript executes the statements in the body of the loop. • At the end of each cycle, JavaScript reevaluates condition to see whether its value has changed. If condition evaluates to false, JavaScript exits from the loop and continues with the statement following the end of the while body.
  • 12. The digitSum Function n result 1729 n sum 1729 0 9 172 11 17 18 1 19 0 19 digitSum(1729) = 19
  • 13. The for Statement for ( init ; test ; step ) { statements to be repeated } Evaluate init, which typically declares a control variable. 1. Evaluate test and exit from the loop if the value is false. 2. Execute the statements in the body of the loop. 3. Evaluate step, which usually updates the control variable. 4. Return to step 2 to begin the next loop cycle. 5. for ( init ; test ; step ) { statements to be repeated } • The for statement in JavaScript is a powerful tool for specifying the structure of a loop independently from the operations the loop performs. The syntax looks like this: • JavaScript evaluates a for statement as follows:
  • 14. Exercise: Reading for Statements Describe the effect of each of the following for statements: This statement executes the loop body ten times, with the control variable i taking on each successive value between 1 and 10. for (let i = 1; i <= 10; i++) 1. This statement executes the loop body n times, with i counting from 0 to n-1. This version is the standard Repeat-n-Times idiom. for (let i = 0; i < n; i++) 2. This statement counts backward from 99 to 1 by twos. for (let n = 99; n >= 1; n -= 2) 3. This statement executes the loop body with the variable x taking on successive powers of two from 1 up to 1024. for (let x = 1; x <= 1024; x *= 2) 4.
  • 15. The factorial Function • The factorial of a number n (which is usually written as n! in mathematics) is defined to be the product of the integers from 1 up to n. Thus, 5! is equal to 120, which is 1x 2x 3x 4x 5. function fact(n) { let result = 1; for (let i = 1; i <= n; i++) { result = result * i; } return result; } • The following function definition uses a for loop to compute the factorial function:
  • 16. The factorialTable Function -> factorialTable(0, 7); min max i 0 7 0 n result i 0 1 1 1 0! = 1 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 6 7 n result i 7 1 1 1 2 2 3 6 4 24 5 120 6 720 7 5040 8 5040 7! = 5040 8 ->
  • 17. Comparing for and while for ( init ; test ; step ) { statements to be repeated } init; while ( test ) { statements to be repeated step; } • The for statement is functionally equivalent to the following code using while: • The advantage of the for statement is that everything you need to know to understand how many times the loop will run is explicitly included in the header line.
  • 19. A Quick Review of Functions • The concept of a function should be familiar to you from prior programming experience. All modern programming languages allow functions to be defined. • At the most basic level, a function is a sequence of statements that has been collected together and given a name. The name makes it possible to execute the statements much more easily; instead of copying out the entire list of statements, you can just provide the function name. • The following terms are useful when working with functions: – Invoking a function by name is known as calling that function. – The caller passes information to a function using arguments. – When a function completes its operation, it returns to its caller. – A function gives information to the caller by returning a result.
  • 20. Review: Syntax of Functions • The general form of a function definition is function name(parameter list) { statements in the function body } where name is the name of the function, and parameter list is a list of variables used to hold the values of each argument. • You can return a value from a function by including one or more return statements, which are usually written as return expression; where expression is an expression that specifies the value you want to return.
  • 21. Nonnumeric Functions • Although functions return a single value, that value can be of any type. • Even without learning the full range of string operations covered in Chapter 7, you can already write string functions that depend only on concatenation, such as the following function that concatenates together n copies of the string str: function concatNCopies(n, str) { let result = ""; for (let i = 0; i < n; i++) { result += str; } return result; }
  • 22. Exercise: Console Pyramid • Write a program that uses the concatNCopies function to display a pyramid on the console in which the bricks are represented by the letter x. The number of levels in the pyramid should be defined as the constant N_LEVELS. • For example, if N_LEVELS is 10, the console output should look like this: ConsolePyramid x xxx xxxxx xxxxxxx xxxxxxxxx xxxxxxxxxxx xxxxxxxxxxxxx xxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxx
  • 23. Predicate Functions • Functions that return Boolean values play a central role in programming and are called predicate functions. As an example, the following function returns true if the first argument is divisible by the second, and false otherwise: function isDivisibleBy(x, y) { return x % y === 0; } • Once you have defined a predicate function, you can use it any conditional expression. For example, you can print the integers between 1 and 100 that are divisible by 7 as follows: for (let i = 1; i <= 100; i++) { if (isDivisibleBy(i, 7)) { println(i); } }
  • 24. Using Predicate Functions Effectively • New programmers often seem uncomfortable with Boolean values and end up writing ungainly code. For example, a beginner might write isDivisibleBy like this: function isDivisibleBy(x, y) { if (x % y === 0) { return true; } else { return false; } } • A similar problem occurs when novices explicitly check to see whether a predicate function returns true. You should be careful to avoid such redundant tests in your own programs. While this code is technically correct, it is inelegant and should be replaced by return x % y === 0.
  • 25. The Purpose of Parameters • In general, functions perform some service to their callers. In order to do so, the function needs to know any details required to carry out the requested task. • Imagine that you were working as a low-level animator at Disney Studies in the days before computerized animation and that one of the senior designers asked you to draw a filled circle. What would you need to know? • At a minimum, you would need to know where the circle should be placed in the frame, how big to make it, and what color it should be. Those values are precisely the information conveyed in the parameters. “All right, Mr. Wiseguy,” she said, “you’re so clever, you tell us what color it should be.” Douglas Adams, The Restaurant at the End of the Universe, 1980 —
  • 26. Libraries • To make programming easier, all modern languages include collections of predefined functions. Those collections are called libraries. • For programming that involves mathematical calculations, the most useful library is the Math library, which includes a number of functions that will be familiar from high-school mathematics (along with many that probably aren’t). A list of the most important functions appears on the next slide. • In JavaScript, each of the functions in the Math library begins with the library name followed by a dot and then the name of the function. For example, the function that calculates square roots is named Math.sqrt. • You call library functions just like any other function, so that calling Math.sqrt(16) returns the value 4.
  • 27. Useful Functions in the Math Library Math.abs(x) Math.max(x, y, . . .) Math.min(x, y, . . .) Math.round(x) Math.floor(x) Math.log(x) Math.pow(x, y) Math.sin(q ) Math.cos(q ) Math.sqrt(x) Math.PI Math.E Math.exp(x) The mathematical constant π The mathematical constant e The absolute value of x The largest of the arguments The smallest of the arguments The closest integer to x The largest integer not exceeding x The natural logarithm of x The inverse logarithm (ex) The value x raised to the y power (xy) The sine of q, measured in radians The cosine of q, measured in radians The square root of x Math.random() A random value between 0 and 1
  • 29. Decomposition • The most effective way to solve a complex problem is to break it down into successively simpler subproblems. • You start by breaking the whole task down into simpler parts. • Some of those tasks may themselves need subdivision. • This process is called stepwise refinement or decomposition. Complete Task Subtask #1 Subtask #2 Subtask #3 Subsubtask #2a Subsubtask #2b
  • 30. Criteria for Choosing a Decomposition The proposed steps should be easy to explain. One indication that you have succeeded is being able to find simple names. 1. The steps should be as general as possible. Programming tools get reused all the time. If your methods perform general tasks, they are much easier to reuse. 2. The steps should make sense at the level of abstraction at which they are used. If you have a method that does the right job but whose name doesn’t make sense in the context of the problem, it is probably worth defining a new method that calls the old one. 3.
  • 31. Exercise: Ruth-Aaron Pairs • Write a program that lists the first NUM_PAIRS Ruth-Aaron pairs. In recreational mathematics, a Ruth-Aaron pair consists of two neighboring integers—e.g. 714 and 715—for which the sum of the distinct prime factors of each are equal. • The pairs are named Ruth-Aaron as a nod to baseball greats Babe Ruth and Hank Aaron. Ruth held the record for most career home runs at 714 until Aaron’s hit his 715th on April 8th, 1974. • If NUM_PAIRS equals 15, the program should publish the output presented on the right.