The document discusses JavaScript basics, including syntax, operators, conditional code, loops, functions, and other fundamental concepts. It provides examples and explanations of JavaScript syntax, basic operators, logical operators, comparison operators, conditional statements like if/else, truthy and falsy values, loops like for, while, and do-while, and functions. The document is intended as an introduction and overview of core JavaScript concepts for readers new to programming.
This document provides an introduction to JavaScript, including its uses, differences from Java, and how code is structured in HTML documents. It outlines objectives like learning operators, loops, functions, objects, event handlers and forms. It also covers JavaScript variables and data types, statements and operators, control structures like conditional statements and loops, and statements like break and continue. The overall purpose is to teach the basics of JavaScript programming.
The document provides information about a JavaScript course including:
1. The course consists of 5 lectures and 5 labs and is evaluated based on projects, assignments, labs and quizzes.
2. The lecture outline covers introduction to JavaScript, syntax, built-in objects and functions.
3. JavaScript was invented by Brendan Eich at Netscape and first appeared in the Netscape Navigator browser in 1995.
This document provides an overview of JavaScript basics including variables, data types, operators, conditional statements, loops, functions, arrays, and error handling. It explains JavaScript syntax, how to include JavaScript code in HTML pages, and commonly used statements like if/else, switch case, while and for loops. It also covers JavaScript functions, returning values from functions, and printing pages. The document describes JavaScript strings and array objects, and their associated methods. Finally, it discusses different types of errors in JavaScript like syntax errors, runtime errors, and logical errors.
Cordova training : Day 3 - Introduction to JavascriptBinu Paul
This document provides an introduction to JavaScript, including:
- JavaScript is a lightweight, interpreted programming language commonly used in web pages.
- Advantages of JavaScript include less server interaction, immediate feedback, and richer interfaces.
- Disadvantages include inability to read/write files for security and lack of multithreading.
- JavaScript syntax can be included in HTML using <script> tags and ignores spaces/newlines.
- Basic data types are strings, numbers, and Booleans, and variables are declared with var.
- Common operators include arithmetic, comparison, logical, and assignment operators.
- Control structures include if/else statements, switch statements, for/while loops.
- Functions are reusable blocks
This document provides an overview of the JavaScript programming language, including its history, key concepts, values, objects, and functions. It summarizes JavaScript as a dynamic language that unifies objects and functions, uses prototype-based inheritance, and loosely typed values. Everything in JavaScript is an object, which can be used to represent records, trees, and other data structures using dynamic object literals.
JavaScript is a versatile programming language primarily used for building dynamic and interactive web applications. Developed by Netscape Communications Corporation in the mid-1990s, JavaScript has since become one of the most popular programming languages worldwide. Here's a detailed description of JavaScript:
Introduction to JavaScript:
JavaScript is a high-level, interpreted programming language that allows developers to add functionality, interactivity, and behavior to web pages. Unlike server-side languages like PHP or Python, JavaScript is executed on the client-side, meaning it runs within the user's web browser. This enables dynamic manipulation of webpage content without requiring communication with the server.
Esoft Metro Campus - Diploma in Web Engineering - (Module V) Programming with JavaScript
(Template - Virtusa Corporate)
Contents:
Introduction to JavaScript
What JavaScript Can Do?
Script tag in HTML
Noscript tag in HTML
Your First JavaScript Program
JavaScript Placement in HTML File
JavaScript Syntax
JavaScript Data Types
JavaScript Variables
JavaScript Identifiers
Arithmetic Operators
String Concatenation Operators
Assignment Operators
Comparison Operators
Logical Operators
Bitwise Operators
If Statement
If… Else Statement
If… Else if… Else Statement
Switch Statement
The ? Operator
While Loop
Do While Loop
For Loop
For…in Loop
break Statement
continue Statement
Arrays
Functions
JavaScript Objects
JavaScript Scope
Strings
Regular Expressions
JavaScript Numbers
Math Object
Date and Time
JavaScript Events
Dialog Boxes
Error Handling in JavaScript
JavaScript Forms Validation
JavaScript HTML DOM
JavaScript BOM
JavaScript is a dynamic programming language originally designed for web browsers but now used in many non-browser environments. It was misunderstood early on due to its name association with Java, inconsistent implementations across browsers, and loose typing. Key features include load-and-go delivery, loose typing where values can be treated as different types, objects used as general containers, prototypal inheritance, and functions as first-class objects. All values in JavaScript are either primitive values (strings, numbers, booleans, null, undefined) or objects.
JavaScript is a scripting language used for web pages that is loosely based on Java. It is built into modern browsers. This document provides an introduction and overview of JavaScript, including its syntax, data types, variables, operators, and control structures like if/else statements and loops. It describes how to write basic JavaScript scripts and embed them in HTML pages.
The JavaScript programming language is a functional language that is commonly misunderstood due to its name, mispositioning, design errors in early implementations, and use in web browsers. It was created in the 1990s and standardized as ECMAScript. JavaScript uses dynamic typing, loose typing, objects as general containers, and prototypal inheritance. Values in JavaScript include numbers, strings, Booleans, objects, null, and undefined. All other values are objects.
The document provides an overview of the JavaScript programming language, including its history, key concepts, values, operators, statements, and objects. It discusses JavaScript's misunderstood nature due to its name, design errors in early implementations, and use in browsers. Some key points made include: JavaScript is a functional language; it uses prototypal inheritance instead of classes; all values are objects except for primitive values; and functions are first-class objects that can be assigned and passed around.
The document provides an overview of the JavaScript programming language, including its history, key concepts, values, operators, statements, functions, and objects. It discusses JavaScript's origins, misunderstandings, dynamic and loosely typed nature, use of prototypes for inheritance rather than classes, and treatment of arrays and objects.
The JavaScript programming language is a multi-paradigm language that is misunderstood due to its name, design errors in early implementations, and use in web browsers. It is a functional language that uses objects, prototypes, and closures. Values in JavaScript include numbers, strings, Booleans, objects, null, and undefined. All other values are objects.
The JavaScript programming language is a multi-paradigm language that is misunderstood due to its name, design errors in early implementations, and use in web browsers. It is a functional language that uses objects, prototypes, and closures. Values in JavaScript include numbers, strings, Booleans, objects, null, and undefined. All other values are objects.
The document discusses different types of loops in JavaScript, including for, do-while, while, labeled, break, continue, for-in, and for-of loops. It provides examples and explanations of how each loop type works, when to use each type, and their basic syntax. The key loops are: for loops repeat until a condition is false, do-while loops always run once then repeat while a condition is true, while loops check a condition before each iteration, and break and continue can terminate or skip iterations within a loop.
The JavaScript Programming Language document provides an overview of the JavaScript programming language, including its history, key concepts, values, operators, statements, and objects. It notes that JavaScript is a multi-paradigm scripting language that is misunderstood as only for web development. The document outlines JavaScript's core data types, objects, functions, and prototypal inheritance model.
This document provides an overview of operators, comparisons, conditionals, strings, arrays, loops, functions, and objects in JavaScript.
It introduces binary operators like addition, subtraction, multiplication, and division. It describes comparison operators like less than, greater than, equality, and inequality. It explains how conditionals like if/else statements can be used to execute code based on conditional expressions. It also covers strings, arrays, loops (while, do/while, for), functions, and objects in JavaScript.
This document provides an overview of JavaScript, including its history, uses, syntax, variables, data types, operators, conditional statements, loops, functions, and ways to display output. Some key points:
- JavaScript is a scripting language used to add interactivity to HTML pages. It was originally developed by Brendan Eich at Netscape under the names Mocha and LiveScript.
- JavaScript code can be embedded within HTML using <script> tags or linked externally via the src attribute. Common uses include form validation, dynamic updating of content, and interactive effects.
- The language supports variables, arrays, objects, numbers, strings, booleans, and other data types. Conditional statements like if
This document provides an overview of a class on JavaScript fundamentals. It includes an agenda covering JS syntax for variables, operators, conditional statements, and loops. It also provides examples and explanations of JS concepts like variable declaration, object properties, arithmetic operators, and for/while loops. The instructor aims to brush up students' coding skills through examples like a simple "alphabet shifter" algorithm to replace each character in a string with the next letter.
This document provides an important notice about final project milestones, links to slides about front end web development (FEWD), instructions for setting up a GitHub repository and copying code files for this week's lesson, and an agenda for reviewing variables, conditionals, functions, and working with arrays and collections of data. Students are instructed to begin writing pseudo code and drafting HTML/CSS for their application and submit it by the end of the 7th week.
The document provides an overview of JavaScript including:
- JavaScript allows client-side scripts to interact with the user and alter web page content.
- JavaScript code is placed within <script> tags and can be included in the <head> or <body> sections of an HTML page.
- Variables, operators, comments, and basic syntax like semicolons are explained. Common data types, arithmetic operators, comparison operators and assignment operators are also covered at a high level.
- Control structures like if/else statements and switch statements allow JavaScript to make decisions and execute code conditionally.
This is the first part (out of two) about basics of JavaScript.
01 What is Dynamic HTML?
02 What is JavaScript?
03 How to JavaScript?
04 JavaScript Syntax
05 JavaScript Basics
06 Conditional Statements
*Order Hemiptera:*
Hemiptera, commonly known as true bugs, is a large and diverse order of insects that includes cicadas, aphids, leafhoppers, and shield bugs. Characterized by their piercing-sucking mouthparts, Hemiptera feed on plant sap, other insects, or small animals. Many species are significant pests, while others are beneficial predators.
*Order Neuroptera:*
Neuroptera, also known as net-winged insects, is an order of insects that includes lacewings, antlions, and owlflies. Characterized by their delicate, net-like wing venation and large, often prominent eyes, Neuroptera are predators that feed on other insects, playing an important role in biological control. Many species have aquatic larvae, adding to their ecological diversity.
Different pricelists for different shops in odoo Point of Sale in Odoo 17Celine George
Price lists are a useful tool for managing the costs of your goods and services. This can assist you in working with other businesses effectively and maximizing your revenues. Additionally, you can provide your customers discounts by using price lists.
More Related Content
Similar to Java Script Basics presentation of program (20)
JavaScript is a versatile programming language primarily used for building dynamic and interactive web applications. Developed by Netscape Communications Corporation in the mid-1990s, JavaScript has since become one of the most popular programming languages worldwide. Here's a detailed description of JavaScript:
Introduction to JavaScript:
JavaScript is a high-level, interpreted programming language that allows developers to add functionality, interactivity, and behavior to web pages. Unlike server-side languages like PHP or Python, JavaScript is executed on the client-side, meaning it runs within the user's web browser. This enables dynamic manipulation of webpage content without requiring communication with the server.
Esoft Metro Campus - Diploma in Web Engineering - (Module V) Programming with JavaScript
(Template - Virtusa Corporate)
Contents:
Introduction to JavaScript
What JavaScript Can Do?
Script tag in HTML
Noscript tag in HTML
Your First JavaScript Program
JavaScript Placement in HTML File
JavaScript Syntax
JavaScript Data Types
JavaScript Variables
JavaScript Identifiers
Arithmetic Operators
String Concatenation Operators
Assignment Operators
Comparison Operators
Logical Operators
Bitwise Operators
If Statement
If… Else Statement
If… Else if… Else Statement
Switch Statement
The ? Operator
While Loop
Do While Loop
For Loop
For…in Loop
break Statement
continue Statement
Arrays
Functions
JavaScript Objects
JavaScript Scope
Strings
Regular Expressions
JavaScript Numbers
Math Object
Date and Time
JavaScript Events
Dialog Boxes
Error Handling in JavaScript
JavaScript Forms Validation
JavaScript HTML DOM
JavaScript BOM
JavaScript is a dynamic programming language originally designed for web browsers but now used in many non-browser environments. It was misunderstood early on due to its name association with Java, inconsistent implementations across browsers, and loose typing. Key features include load-and-go delivery, loose typing where values can be treated as different types, objects used as general containers, prototypal inheritance, and functions as first-class objects. All values in JavaScript are either primitive values (strings, numbers, booleans, null, undefined) or objects.
JavaScript is a scripting language used for web pages that is loosely based on Java. It is built into modern browsers. This document provides an introduction and overview of JavaScript, including its syntax, data types, variables, operators, and control structures like if/else statements and loops. It describes how to write basic JavaScript scripts and embed them in HTML pages.
The JavaScript programming language is a functional language that is commonly misunderstood due to its name, mispositioning, design errors in early implementations, and use in web browsers. It was created in the 1990s and standardized as ECMAScript. JavaScript uses dynamic typing, loose typing, objects as general containers, and prototypal inheritance. Values in JavaScript include numbers, strings, Booleans, objects, null, and undefined. All other values are objects.
The document provides an overview of the JavaScript programming language, including its history, key concepts, values, operators, statements, and objects. It discusses JavaScript's misunderstood nature due to its name, design errors in early implementations, and use in browsers. Some key points made include: JavaScript is a functional language; it uses prototypal inheritance instead of classes; all values are objects except for primitive values; and functions are first-class objects that can be assigned and passed around.
The document provides an overview of the JavaScript programming language, including its history, key concepts, values, operators, statements, functions, and objects. It discusses JavaScript's origins, misunderstandings, dynamic and loosely typed nature, use of prototypes for inheritance rather than classes, and treatment of arrays and objects.
The JavaScript programming language is a multi-paradigm language that is misunderstood due to its name, design errors in early implementations, and use in web browsers. It is a functional language that uses objects, prototypes, and closures. Values in JavaScript include numbers, strings, Booleans, objects, null, and undefined. All other values are objects.
The JavaScript programming language is a multi-paradigm language that is misunderstood due to its name, design errors in early implementations, and use in web browsers. It is a functional language that uses objects, prototypes, and closures. Values in JavaScript include numbers, strings, Booleans, objects, null, and undefined. All other values are objects.
The document discusses different types of loops in JavaScript, including for, do-while, while, labeled, break, continue, for-in, and for-of loops. It provides examples and explanations of how each loop type works, when to use each type, and their basic syntax. The key loops are: for loops repeat until a condition is false, do-while loops always run once then repeat while a condition is true, while loops check a condition before each iteration, and break and continue can terminate or skip iterations within a loop.
The JavaScript Programming Language document provides an overview of the JavaScript programming language, including its history, key concepts, values, operators, statements, and objects. It notes that JavaScript is a multi-paradigm scripting language that is misunderstood as only for web development. The document outlines JavaScript's core data types, objects, functions, and prototypal inheritance model.
This document provides an overview of operators, comparisons, conditionals, strings, arrays, loops, functions, and objects in JavaScript.
It introduces binary operators like addition, subtraction, multiplication, and division. It describes comparison operators like less than, greater than, equality, and inequality. It explains how conditionals like if/else statements can be used to execute code based on conditional expressions. It also covers strings, arrays, loops (while, do/while, for), functions, and objects in JavaScript.
This document provides an overview of JavaScript, including its history, uses, syntax, variables, data types, operators, conditional statements, loops, functions, and ways to display output. Some key points:
- JavaScript is a scripting language used to add interactivity to HTML pages. It was originally developed by Brendan Eich at Netscape under the names Mocha and LiveScript.
- JavaScript code can be embedded within HTML using <script> tags or linked externally via the src attribute. Common uses include form validation, dynamic updating of content, and interactive effects.
- The language supports variables, arrays, objects, numbers, strings, booleans, and other data types. Conditional statements like if
This document provides an overview of a class on JavaScript fundamentals. It includes an agenda covering JS syntax for variables, operators, conditional statements, and loops. It also provides examples and explanations of JS concepts like variable declaration, object properties, arithmetic operators, and for/while loops. The instructor aims to brush up students' coding skills through examples like a simple "alphabet shifter" algorithm to replace each character in a string with the next letter.
This document provides an important notice about final project milestones, links to slides about front end web development (FEWD), instructions for setting up a GitHub repository and copying code files for this week's lesson, and an agenda for reviewing variables, conditionals, functions, and working with arrays and collections of data. Students are instructed to begin writing pseudo code and drafting HTML/CSS for their application and submit it by the end of the 7th week.
The document provides an overview of JavaScript including:
- JavaScript allows client-side scripts to interact with the user and alter web page content.
- JavaScript code is placed within <script> tags and can be included in the <head> or <body> sections of an HTML page.
- Variables, operators, comments, and basic syntax like semicolons are explained. Common data types, arithmetic operators, comparison operators and assignment operators are also covered at a high level.
- Control structures like if/else statements and switch statements allow JavaScript to make decisions and execute code conditionally.
This is the first part (out of two) about basics of JavaScript.
01 What is Dynamic HTML?
02 What is JavaScript?
03 How to JavaScript?
04 JavaScript Syntax
05 JavaScript Basics
06 Conditional Statements
*Order Hemiptera:*
Hemiptera, commonly known as true bugs, is a large and diverse order of insects that includes cicadas, aphids, leafhoppers, and shield bugs. Characterized by their piercing-sucking mouthparts, Hemiptera feed on plant sap, other insects, or small animals. Many species are significant pests, while others are beneficial predators.
*Order Neuroptera:*
Neuroptera, also known as net-winged insects, is an order of insects that includes lacewings, antlions, and owlflies. Characterized by their delicate, net-like wing venation and large, often prominent eyes, Neuroptera are predators that feed on other insects, playing an important role in biological control. Many species have aquatic larvae, adding to their ecological diversity.
Different pricelists for different shops in odoo Point of Sale in Odoo 17Celine George
Price lists are a useful tool for managing the costs of your goods and services. This can assist you in working with other businesses effectively and maximizing your revenues. Additionally, you can provide your customers discounts by using price lists.
How to Create an Event in Odoo 18 - Odoo 18 SlidesCeline George
Creating an event in Odoo 18 is a straightforward process that allows you to manage various aspects of your event efficiently.
Odoo 18 Events Module is a powerful tool for organizing and managing events of all sizes, from conferences and workshops to webinars and meetups.
Strengthened Senior High School - Landas Tool Kit.pptxSteffMusniQuiballo
Landas Tool Kit is a very helpful guide in guiding the Senior High School students on their SHS academic journey. It will pave the way on what curriculum exits will they choose and fit in.
A short update and next week. I am writing both Session 9 and Orientation S1.
As a Guest Student,
You are now upgraded to Grad Level.
See Uploads for “Student Checkin” & “S8”. Thx.
Thank you for attending our workshops.
If you are new, do welcome.
Grad Students: I am planning a Reiki-Yoga Master Course (As a package). I’m Fusing both together.
This will include the foundation of each practice. Our Free Workshops can be used with any Reiki Yoga training package. Traditional Reiki does host rules and ethics. Its silent and within the JP Culture/Area/Training/Word of Mouth. It allows remote healing but there’s limits As practitioners and masters. We are not allowed to share certain secrets/tools. Some content is designed only for “Masters”. Some yoga are similar like the Kriya Yoga-Church (Vowed Lessons). We will review both Reiki and Yoga (Master tools) in the Course upcoming.
Session Practice, For Reference:
Before starting a session, Make sure to check your environment. Nothing stressful. Later, You can decorate a space as well.
Check the comfort level, any needed resources (Yoga/Reiki/Spa Props), or Meditation Asst?
Props can be oils, sage, incense, candles, crystals, pillows, blankets, yoga mat, any theme applies.
Select your comfort Pose. This can be standing, sitting, laying down, or a combination.
Monitor your breath. You can add exercises.
Add any mantras or affirmations. This does aid mind and spirit. It helps you to focus.
Also you can set intentions using a candle.
The Yoga-key is balancing mind, body, and spirit.
Finally, The Duration can be long or short.
Its a good session base for any style.
Next Week’s Focus:
A continuation of Intuition Development. We will review the Chakra System - Our temple. A misguided, misused situation lol. This will also serve Attunement later.
For Sponsor,
General updates,
& Donations:
Please visit:
https://ldmchapels.weebly.com
Rose Cultivation Practices by Kushal Lamichhane.pdfkushallamichhame
This includes the overall cultivation practices of Rose prepared by:
Kushal Lamichhane (AKL)
Instructor
Shree Gandhi Adarsha Secondary School
Kageshowri Manohara-09, Kathmandu, Nepal
Adam Grant: Transforming Work Culture Through Organizational PsychologyPrachi Shah
This presentation explores the groundbreaking work of Adam Grant, renowned organizational psychologist and bestselling author. It highlights his key theories on giving, motivation, leadership, and workplace dynamics that have revolutionized how organizations think about productivity, collaboration, and employee well-being. Ideal for students, HR professionals, and leadership enthusiasts, this deck includes insights from his major works like Give and Take, Originals, and Think Again, along with interactive elements for enhanced engagement.
Artificial intelligence Presented by JM.jmansha170
AI (Artificial Intelligence) :
"AI is the ability of machines to mimic human intelligence, such as learning, decision-making, and problem-solving."
Important Points about AI:
1. Learning – AI can learn from data (Machine Learning).
2. Automation – It helps automate repetitive tasks.
3. Decision Making – AI can analyze and make decisions faster than humans.
4. Natural Language Processing (NLP) – AI can understand and generate human language.
5. Vision & Recognition – AI can recognize images, faces, and patterns.
6. Used In – Healthcare, finance, robotics, education, and more.
Owner By:
Name : Junaid Mansha
Work : Web Developer and Graphics Designer
Contact us : +92 322 2291672
Email : [email protected]
Slides from a Capitol Technology University presentation covering doctoral programs offered by the university. All programs are online, and regionally accredited. The presentation covers degree program details, tuition, financial aid and the application process.
Unit- 4 Biostatistics & Research Methodology.pdfKRUTIKA CHANNE
Blocking and confounding (when a third variable, or confounder, influences both the exposure and the outcome) system for Two-level factorials (a type of experimental design where each factor (independent variable) is investigated at only two levels, typically denoted as "high" and "low" or "+1" and "-1")
Regression modeling (statistical model that estimates the relationship between one dependent variable and one or more independent variables using a line): Hypothesis testing in Simple and Multiple regression models
Introduction to Practical components of Industrial and Clinical Trials Problems: Statistical Analysis Using Excel, SPSS, MINITAB®️, DESIGN OF EXPERIMENTS, R - Online Statistical Software to Industrial and Clinical trial approach
This presentation was provided by Jennifer Gibson of Dryad, during the first session of our 2025 NISO training series "Secrets to Changing Behavior in Scholarly Communications." Session One was held June 5, 2025.
How to Create a Rainbow Man Effect in Odoo 18Celine George
In Odoo 18, the Rainbow Man animation adds a playful and motivating touch to task completion. This cheerful effect appears after specific user actions, like marking a CRM opportunity as won. It’s designed to enhance user experience by making routine tasks more engaging.
Ray Dalio How Countries go Broke the Big CycleDadang Solihin
A complete and practical understanding of the Big Debt Cycle. A much more practical understanding of how supply and demand really work compared to the conventional economic thinking. A complete and practical understanding of the Overall Big Cycle, which is driven by the Big Debt Cycle and the other major cycles, including the big political cycle within countries that changes political orders and the big geopolitical cycle that changes world orders.
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.