SlideShare a Scribd company logo
1 of 37
JAVASCRIPT
SCRIPT OF THE INTERNET
WHAT IS JAVASCRIPT?
The de facto scripting language on the Web.

Powerful, versatile, ubiquitous.
Every personal computer in the world uses it because…
Every modern browser implements it.
It has started to supplant Flash.
JAVASCRIPT ORIGINS
Mid-90s

At Netscape (built to go head-to-head with MS’s VB)
Originally: validated forms
Originally: minimal page manipulation
Now: Build rich client-side apps
CHAPTER ONE

SETTING UP
THE BROWSER
CONSOLE
1. Google Chrome
(CTRL+SHIFT+J)
Mac (option command J)

1. Firefox
(CTRL+SHIFT+K)
Mac (option command K)

1. Internet Explorer
(F12)
Safari = Enable with “command comma”,
check “Show Develop Menu”
Later: option command C

Hi
IN HTML CODE
Inline

Separate file

<script>

<script src=“hello.js”>
</script>

alert(“Hello, world!”);
</script>
LOADING SCRIPTS
1. In the page’s onload function
2. Immediately before the closing </body> tag

(You cannot execute JavaScript before the objects on the page it
will interact with are created.)
(onload only runs after all the img tags (and everything) are
loaded, so to run JS before that, use the latter method.)
CHAPTER TWO

VARIABLES
PROGRAMMING IS…
Programming

Data Manipulation
Store Data
Words

Phrases

• name
• tax
• length
• width

• firstName
• taskList
• timeToLive
Camel casing (first letter of subsequent words = capital)
COMMENTS ARE…
Non-executing bits of code to describe what is happening.

Inline: //this is a Javascript comment
Multiline: /* this style is similar
to CSS style comments
*/
DECLARATIONS ARE…
var task = “Make an assignment.”;

(String)

var complete = true;

(Boolean)

var task = “Make an assignment.”,

(Multi)

complete = true;

(Remember to terminate it)

(Note: JS is case sensitive, so task and Task are different.)
(Note: We are declaring and initializing variables here. You can do
each separately. – Next slide)
…JUST THE BEGINNING
// variable declaration

var task, complete;
// variable initialization (assign a value)
task = “Make an assignment.”;
complete = true;

(Note: This is better for debugging.)
THE 6 DATA TYPES ARE…
(Note: JavaScript is loosely typed – i.e. you don’t need to declare types)
you can change types on a whim

object
null

number

Boolean
string

undefined
DATATYPE: number
Numbers can include:

1. All possible number values
2. *Special Not-a-Number (NaN) values
3. Positive infinity
4. Negative infinity
NaN ASIDE
NaN = when math/parse functions don’t return a number

NaN = the only value that doesn’t equal itself
NaN==NaN and NaN===NaN return false (the best test) – 2 markers demo
isNaN() function:
1.

Converts the value to a number (type conversion)
isNaN(NaN) = true
isNaN(undefined) = true
isNan({}) = true
isNaN(true) = false
isNaN(null) = false

isNaN(“42”) = false
isNaN(“”) = false
isNaN(“
”) = false
isNaN(“foo”) = true
DATATYPE: string
Strings are:

1. Anything treated as text
2. Surrounded by quotation marks “ ”
3. “Hello, world!”
4. “1, 2, 3, 4, 5”
5. “!@#$%^&*()_+”
DATATYPE: Boolean
Booleans (capital B) are:

1. True
2. False
DATATYPE: undefined
Undefined variables are:

1. Declared variables
2. With no values assigned to them
DATATYPE: null
Null variables are:

1. Declared variables
2. Specifically assigned null (absent value)
DATATYPE: object
Objects are:

1. A collection of properties
2. Properties can include any previous type
3. Can also include other objects
4. Can also include functions
OPERATIONS ARE…
Concatenate strings (+)

Math: +, -, *, /, % (R)
% = Remainder
10%3 = 1

var fname, lname, fullName;

var
provincial, federal, subtot
al, total;

fname = “John”;
lname = “Doe”;
fullName = fname + “ ” +
lname; // fullName is “John
Doe”

provincial = 0.095;
federal = 0.05;
subtotal = 10;
total = subtotal +
(subtotal * provincial) +
(subtotal * federal);
// total is 11.45
LOOSE TYPING
TROUBLE
John has 11 tasks, Jane has 42. We want to add them.
var johnTaskCount = 11, janeTaskCount = “42”,
totalTaskCount = johnTaskCount + janeTaskCount;
// this produces “1142” because of the string
var johnTaskCount = 11, janeTaskCount = 42,
totalTaskCount = johnTaskCount + janeTaskCount;
// this produces 53
This is Type Conversion.
Number + string = change Number to string & concat
Number + Boolean = change Boolean to number (1 = T, 0 = F) & add
THE 8 COMPARISON OPS ARE…
(Note: Compare two values and return either true or false)

Greater
than
>

Equal
==

Greater
than or
Equal to
>=

Strict Equal
===
Less than
<

Not Equal
!=
Strict Not
Equal
!==

Less than
or Equal to
<=
COMPARISON OP: ==
If not the same type, JS
converts, then compares:

1.

Number + Boolean =
convert both to numbers

2.

String? = convert both to
strings

3.

Object? = true if both
refer to same memory
location

Example:

1 == 1
“1” == 1
1 == true
0 == false
“” == 0
“ ” == 0

//
//
//
//
//
//

returns
returns
returns
returns
returns
returns

true
true (“1” converts to 1)
true
true
true (“” converts to 0)
true (“ ” converts to 0)

0 == 1
// returns false
1 == false // returns false
0 == true // returns false
var x, y;
x = {};
y = x;
x == y;
x == {};

//
//
//
//
//

declare x and y
create object and assign x to it
point y to x
returns true (same object in memory)
returns false (not the same object)
COMPARISON OP: !=
Same as previous, but
opposite.

Example:

1 != 1
“1” != 1
1 != true
0 != false
“” != 0
“ ” != 0

//
//
//
//
//
//

returns
returns
returns
returns
returns
returns

false
false (“1” converts to 1)
false
false
false (“” converts to 0)
false (“ ” converts to 0)

0 != 1
// returns true
1 != false // returns true
0 != true // returns true
var x, y;
x = {};
y = x;
x != y;
x != {};

//
//
//
//
//

declare x and y
create object and assign x to it
point y to x
returns false (same object in mem)
returns true (not the same object)
COMPARISON OP: ===
Strict Equal = no conversion
of types

Example:

1 === 1
“1” === 1
1 === true
0 === false
“” === 0
“ ” === 0

//
//
//
//
//
//

returns
returns
returns
returns
returns
returns

true
false (“1” not converted)
false
false
false (“” not converted)
false (“ ” not converted)

0 === 1
// returns false
1 === false // returns false
0 === true // returns false
var x, y;
x = {};
y = x;
x === y;
x === {};

//
//
//
//
//

declare x and y
create object and assign x to it
point y to x
returns true (same object in mem)
returns false (not the same object)
COMPARISON OP: !==
Same as previous, but
opposite.

Example:

1 !== 1
“1” !== 1
1 !== true
0 !== false
“” !== 0
“ ” !== 0

//
//
//
//
//
//

returns
returns
returns
returns
returns
returns

false
true (“1” not converted)
true
true
true (“” not converted)
true (“ ” not converted)

0 !== 1
// returns true
1 !== false // returns true
0 !== true // returns true
var x, y;
x = {};
y = x;
x !== y;
x !== {};

//
//
//
//
//

declare x and y
create object and assign x to it
point y to x
returns false (same object in mem)
returns true (not the same object)
COMPARISON OP: >, >=
Type conversion implicitly
occurs before comparison.

Example:

0
1
2
2

>
>
>
>

1
1
1
“”

//
//
//
//

returns
returns
returns
returns

false
false
true
true (“” converts to 0)

0 >= 1
// returns false
1 >= 1
// returns true
“1” >= 1 // returns true (“1” converts to 1)
COMPARISON OP: <, <=
Same as previous, but less
than.

Example:

0
1
2
2

<
<
<
<

1
1
1
“”

//
//
//
//

returns
returns
returns
returns

0 <= 1
// returns
1 <= 1
// returns
“1” <= 1 // returns
2 <= 1
// returns
“2” <= 1 // returns

true
false
false
false (“” converts to 0)
true
true
true (“1” converts to 1)
false
false (“2” converts to 2)
THE 3 LOGIC OPERATORS ARE…
(Note: These convert values to Booleans and return one of the values.)

Logic AND
&&
Logic NOT
!
Logic OR
||
LOGIC OP: &&
If the first of two values =
false, it is returned;
otherwise the second value
is returned.

Example:

true && true;
true && false;
false && true;
0 && 1;
0 && 2;
1 && 0;
2 && 0;
“foo” && “bar”;

//
//
//
//
//
//
//
//

returns
returns
returns
returns
returns
returns
returns
returns

true
false
false
0
0
0
0
“bar”
LOGIC OP: ||
If the first of two values =
true, it is returned; otherwise
the second value is returned.

Example:

true || true;
true || false;
false || true;
0 || 1;
0 || 2;
1 || 0;
2 || 0;
“foo” || “bar”;

//
//
//
//
//
//
//
//

returns
returns
returns
returns
returns
returns
returns
returns

true
true
true
1
2
1
2
foo
LOGIC OP: !
It inverts the Boolean value.

Example:

!true;
!false;
!0;
!1;
!“foo”;

//
//
//
//
//

returns
returns
returns
returns
returns

false
true
true
false
false
LOGICAL FLOW IS…
We use if…else statements
and logical operators to
evaluate conditions and fork
code execution.
Which path should we take?
CODE FOR ABOVE
EXAMPLE
var d, hours, minutes, time, message;
// Get the current time’s hour and minute
components
d = new Date();
hours = d.getHours();
minutes = d.getMinutes();
// Make sure the hour is a double digit
string
if (hours < 10) {
hours = “0” + hours; // converts hours
to string
} else {
hours = hours.toString();
}
//Make sure the minutes are a double
digit string
if (minutes < 10) {
minutes = “0” + minutes; // converts

minutes to string
} else {
minutes = minutes.toString();
}
// Concatenate hours and minutes into a
quadruple digit number representing the
time in 24-hour format
time = Number(hours + minutes);
if (time >= 0000 && time < 1200) {
message = “Good morning!”;
} else if (time >= 1200 && time < 1700) {
message = “Good afternoon!”;
} else if (time >= 1700 && time < 2100) {
message = “Good evening!”;
} else if (time >= 2100 && time <=2359) {
message = “Good night!”;
}
alert(message);
WITH TERNARY OPERATOR
var d, hours, minutes, time, message;
// Get the current time’s hour and minute
components
d = new Date();
hours = d.getHours();
minutes = d.getMinutes();
// Make sure the hour is a double digit
string
hours = (hours < 10) ? “0” + hours :
hours.toString();
// Make sure the minutes are a double
digit string
minutes = (minutes < 10) ? “0” + minutes
: minutes.toString();
// Concatenate hours and minutes into a
quadruple digit number representing the
time in 24-hour format

time = Number(hours + minutes);
message = (time >= 0000 && time < 1200) ?
“Good morning!” :
(time >= 1200 && time < 1700) ?
“Good afternoon!” :
(time >= 1700 && time < 2100) ?
“Good evening!” :
(time >= 2100 && time <=2359) ?
“Good night!”;
alert(message);

Ternary Operator = shortened if…else
condition ? expression1 : expression2;
PROJECT 1.0
Create a Task Manager

Make a .js file and add this code
var task1, task2, task3;

task1 = “Pay phone bill”;
task2 = “Write best-selling novel”;
task3 = “Walk the dog”;

More Related Content

What's hot

Stuff you didn't know about action script
Stuff you didn't know about action scriptStuff you didn't know about action script
Stuff you didn't know about action script
Christophe Herreman
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
Stoyan Stefanov
 

What's hot (20)

JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To Closure
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
Stuff you didn't know about action script
Stuff you didn't know about action scriptStuff you didn't know about action script
Stuff you didn't know about action script
 
Programming Language Swift Overview
Programming Language Swift OverviewProgramming Language Swift Overview
Programming Language Swift Overview
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
 
Swift Introduction
Swift IntroductionSwift Introduction
Swift Introduction
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!
 
Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScript
 
ES6 in Production [JSConfUY2015]
ES6 in Production [JSConfUY2015]ES6 in Production [JSConfUY2015]
ES6 in Production [JSConfUY2015]
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
 
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
 
Cocoa Design Patterns in Swift
Cocoa Design Patterns in SwiftCocoa Design Patterns in Swift
Cocoa Design Patterns in Swift
 
Javascript Primer
Javascript PrimerJavascript Primer
Javascript Primer
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
Introduction to Swift programming language.
Introduction to Swift programming language.Introduction to Swift programming language.
Introduction to Swift programming language.
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?
 
Short intro to ECMAScript
Short intro to ECMAScriptShort intro to ECMAScript
Short intro to ECMAScript
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
 

Similar to JavaScript 1 for high school

Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
Varun C M
 

Similar to JavaScript 1 for high school (20)

Ruby Gotchas
Ruby GotchasRuby Gotchas
Ruby Gotchas
 
Javascript essentials
Javascript essentialsJavascript essentials
Javascript essentials
 
DIWE - Fundamentals of PHP
DIWE - Fundamentals of PHPDIWE - Fundamentals of PHP
DIWE - Fundamentals of PHP
 
DIWE - Programming with JavaScript
DIWE - Programming with JavaScriptDIWE - Programming with JavaScript
DIWE - Programming with JavaScript
 
Introduction to Kotlin.pptx
Introduction to Kotlin.pptxIntroduction to Kotlin.pptx
Introduction to Kotlin.pptx
 
01 Introduction to Kotlin - Programming in Kotlin.pptx
01 Introduction to Kotlin - Programming in Kotlin.pptx01 Introduction to Kotlin - Programming in Kotlin.pptx
01 Introduction to Kotlin - Programming in Kotlin.pptx
 
Javascript
JavascriptJavascript
Javascript
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
Javascript
JavascriptJavascript
Javascript
 
JavaScript Essentials in 1 Hour (2018)
JavaScript Essentials in 1 Hour (2018)JavaScript Essentials in 1 Hour (2018)
JavaScript Essentials in 1 Hour (2018)
 
Ruby Gotchas
Ruby GotchasRuby Gotchas
Ruby Gotchas
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
Ceylon idioms by Gavin King
Ceylon idioms by Gavin KingCeylon idioms by Gavin King
Ceylon idioms by Gavin King
 
Douglas Crockford - Programming Style and Your Brain
Douglas Crockford - Programming Style and Your BrainDouglas Crockford - Programming Style and Your Brain
Douglas Crockford - Programming Style and Your Brain
 
Ur Domain Haz Monoids DDDx NYC 2014
Ur Domain Haz Monoids DDDx NYC 2014Ur Domain Haz Monoids DDDx NYC 2014
Ur Domain Haz Monoids DDDx NYC 2014
 
SNP STEAM Academy 2017 Class #12
SNP STEAM Academy 2017 Class #12SNP STEAM Academy 2017 Class #12
SNP STEAM Academy 2017 Class #12
 
JVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in KotlinJVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in Kotlin
 
JavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talkJavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talk
 
The Swift Programming Language - Xcode6 for iOS App Development - AgileInfowa...
The Swift Programming Language - Xcode6 for iOS App Development - AgileInfowa...The Swift Programming Language - Xcode6 for iOS App Development - AgileInfowa...
The Swift Programming Language - Xcode6 for iOS App Development - AgileInfowa...
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 

More from jekkilekki

WordPress for Education PPT
WordPress for Education PPTWordPress for Education PPT
WordPress for Education PPT
jekkilekki
 

More from jekkilekki (7)

Aicf website upgrade 2010 presentation
Aicf website upgrade 2010 presentationAicf website upgrade 2010 presentation
Aicf website upgrade 2010 presentation
 
서울 미트업 2015 오픈 소스, 워드프레스, 그리고 커뮤니티
서울 미트업 2015   오픈 소스, 워드프레스, 그리고 커뮤니티서울 미트업 2015   오픈 소스, 워드프레스, 그리고 커뮤니티
서울 미트업 2015 오픈 소스, 워드프레스, 그리고 커뮤니티
 
Computer B Course Intro - GPA High School
Computer B Course Intro - GPA High SchoolComputer B Course Intro - GPA High School
Computer B Course Intro - GPA High School
 
Report Writing Tips
Report Writing TipsReport Writing Tips
Report Writing Tips
 
A/an grammar
A/an grammarA/an grammar
A/an grammar
 
WordPress for Education PPT
WordPress for Education PPTWordPress for Education PPT
WordPress for Education PPT
 
KOTESOL Gradebook Presentation
KOTESOL Gradebook PresentationKOTESOL Gradebook Presentation
KOTESOL Gradebook Presentation
 

Recently uploaded

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Recently uploaded (20)

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 

JavaScript 1 for high school

  • 2. WHAT IS JAVASCRIPT? The de facto scripting language on the Web. Powerful, versatile, ubiquitous. Every personal computer in the world uses it because… Every modern browser implements it. It has started to supplant Flash.
  • 3. JAVASCRIPT ORIGINS Mid-90s At Netscape (built to go head-to-head with MS’s VB) Originally: validated forms Originally: minimal page manipulation Now: Build rich client-side apps
  • 5. THE BROWSER CONSOLE 1. Google Chrome (CTRL+SHIFT+J) Mac (option command J) 1. Firefox (CTRL+SHIFT+K) Mac (option command K) 1. Internet Explorer (F12) Safari = Enable with “command comma”, check “Show Develop Menu” Later: option command C Hi
  • 6. IN HTML CODE Inline Separate file <script> <script src=“hello.js”> </script> alert(“Hello, world!”); </script>
  • 7. LOADING SCRIPTS 1. In the page’s onload function 2. Immediately before the closing </body> tag (You cannot execute JavaScript before the objects on the page it will interact with are created.) (onload only runs after all the img tags (and everything) are loaded, so to run JS before that, use the latter method.)
  • 9. PROGRAMMING IS… Programming Data Manipulation Store Data Words Phrases • name • tax • length • width • firstName • taskList • timeToLive Camel casing (first letter of subsequent words = capital)
  • 10. COMMENTS ARE… Non-executing bits of code to describe what is happening. Inline: //this is a Javascript comment Multiline: /* this style is similar to CSS style comments */
  • 11. DECLARATIONS ARE… var task = “Make an assignment.”; (String) var complete = true; (Boolean) var task = “Make an assignment.”, (Multi) complete = true; (Remember to terminate it) (Note: JS is case sensitive, so task and Task are different.) (Note: We are declaring and initializing variables here. You can do each separately. – Next slide)
  • 12. …JUST THE BEGINNING // variable declaration var task, complete; // variable initialization (assign a value) task = “Make an assignment.”; complete = true; (Note: This is better for debugging.)
  • 13. THE 6 DATA TYPES ARE… (Note: JavaScript is loosely typed – i.e. you don’t need to declare types) you can change types on a whim object null number Boolean string undefined
  • 14. DATATYPE: number Numbers can include: 1. All possible number values 2. *Special Not-a-Number (NaN) values 3. Positive infinity 4. Negative infinity
  • 15. NaN ASIDE NaN = when math/parse functions don’t return a number NaN = the only value that doesn’t equal itself NaN==NaN and NaN===NaN return false (the best test) – 2 markers demo isNaN() function: 1. Converts the value to a number (type conversion) isNaN(NaN) = true isNaN(undefined) = true isNan({}) = true isNaN(true) = false isNaN(null) = false isNaN(“42”) = false isNaN(“”) = false isNaN(“ ”) = false isNaN(“foo”) = true
  • 16. DATATYPE: string Strings are: 1. Anything treated as text 2. Surrounded by quotation marks “ ” 3. “Hello, world!” 4. “1, 2, 3, 4, 5” 5. “!@#$%^&*()_+”
  • 17. DATATYPE: Boolean Booleans (capital B) are: 1. True 2. False
  • 18. DATATYPE: undefined Undefined variables are: 1. Declared variables 2. With no values assigned to them
  • 19. DATATYPE: null Null variables are: 1. Declared variables 2. Specifically assigned null (absent value)
  • 20. DATATYPE: object Objects are: 1. A collection of properties 2. Properties can include any previous type 3. Can also include other objects 4. Can also include functions
  • 21. OPERATIONS ARE… Concatenate strings (+) Math: +, -, *, /, % (R) % = Remainder 10%3 = 1 var fname, lname, fullName; var provincial, federal, subtot al, total; fname = “John”; lname = “Doe”; fullName = fname + “ ” + lname; // fullName is “John Doe” provincial = 0.095; federal = 0.05; subtotal = 10; total = subtotal + (subtotal * provincial) + (subtotal * federal); // total is 11.45
  • 22. LOOSE TYPING TROUBLE John has 11 tasks, Jane has 42. We want to add them. var johnTaskCount = 11, janeTaskCount = “42”, totalTaskCount = johnTaskCount + janeTaskCount; // this produces “1142” because of the string var johnTaskCount = 11, janeTaskCount = 42, totalTaskCount = johnTaskCount + janeTaskCount; // this produces 53 This is Type Conversion. Number + string = change Number to string & concat Number + Boolean = change Boolean to number (1 = T, 0 = F) & add
  • 23. THE 8 COMPARISON OPS ARE… (Note: Compare two values and return either true or false) Greater than > Equal == Greater than or Equal to >= Strict Equal === Less than < Not Equal != Strict Not Equal !== Less than or Equal to <=
  • 24. COMPARISON OP: == If not the same type, JS converts, then compares: 1. Number + Boolean = convert both to numbers 2. String? = convert both to strings 3. Object? = true if both refer to same memory location Example: 1 == 1 “1” == 1 1 == true 0 == false “” == 0 “ ” == 0 // // // // // // returns returns returns returns returns returns true true (“1” converts to 1) true true true (“” converts to 0) true (“ ” converts to 0) 0 == 1 // returns false 1 == false // returns false 0 == true // returns false var x, y; x = {}; y = x; x == y; x == {}; // // // // // declare x and y create object and assign x to it point y to x returns true (same object in memory) returns false (not the same object)
  • 25. COMPARISON OP: != Same as previous, but opposite. Example: 1 != 1 “1” != 1 1 != true 0 != false “” != 0 “ ” != 0 // // // // // // returns returns returns returns returns returns false false (“1” converts to 1) false false false (“” converts to 0) false (“ ” converts to 0) 0 != 1 // returns true 1 != false // returns true 0 != true // returns true var x, y; x = {}; y = x; x != y; x != {}; // // // // // declare x and y create object and assign x to it point y to x returns false (same object in mem) returns true (not the same object)
  • 26. COMPARISON OP: === Strict Equal = no conversion of types Example: 1 === 1 “1” === 1 1 === true 0 === false “” === 0 “ ” === 0 // // // // // // returns returns returns returns returns returns true false (“1” not converted) false false false (“” not converted) false (“ ” not converted) 0 === 1 // returns false 1 === false // returns false 0 === true // returns false var x, y; x = {}; y = x; x === y; x === {}; // // // // // declare x and y create object and assign x to it point y to x returns true (same object in mem) returns false (not the same object)
  • 27. COMPARISON OP: !== Same as previous, but opposite. Example: 1 !== 1 “1” !== 1 1 !== true 0 !== false “” !== 0 “ ” !== 0 // // // // // // returns returns returns returns returns returns false true (“1” not converted) true true true (“” not converted) true (“ ” not converted) 0 !== 1 // returns true 1 !== false // returns true 0 !== true // returns true var x, y; x = {}; y = x; x !== y; x !== {}; // // // // // declare x and y create object and assign x to it point y to x returns false (same object in mem) returns true (not the same object)
  • 28. COMPARISON OP: >, >= Type conversion implicitly occurs before comparison. Example: 0 1 2 2 > > > > 1 1 1 “” // // // // returns returns returns returns false false true true (“” converts to 0) 0 >= 1 // returns false 1 >= 1 // returns true “1” >= 1 // returns true (“1” converts to 1)
  • 29. COMPARISON OP: <, <= Same as previous, but less than. Example: 0 1 2 2 < < < < 1 1 1 “” // // // // returns returns returns returns 0 <= 1 // returns 1 <= 1 // returns “1” <= 1 // returns 2 <= 1 // returns “2” <= 1 // returns true false false false (“” converts to 0) true true true (“1” converts to 1) false false (“2” converts to 2)
  • 30. THE 3 LOGIC OPERATORS ARE… (Note: These convert values to Booleans and return one of the values.) Logic AND && Logic NOT ! Logic OR ||
  • 31. LOGIC OP: && If the first of two values = false, it is returned; otherwise the second value is returned. Example: true && true; true && false; false && true; 0 && 1; 0 && 2; 1 && 0; 2 && 0; “foo” && “bar”; // // // // // // // // returns returns returns returns returns returns returns returns true false false 0 0 0 0 “bar”
  • 32. LOGIC OP: || If the first of two values = true, it is returned; otherwise the second value is returned. Example: true || true; true || false; false || true; 0 || 1; 0 || 2; 1 || 0; 2 || 0; “foo” || “bar”; // // // // // // // // returns returns returns returns returns returns returns returns true true true 1 2 1 2 foo
  • 33. LOGIC OP: ! It inverts the Boolean value. Example: !true; !false; !0; !1; !“foo”; // // // // // returns returns returns returns returns false true true false false
  • 34. LOGICAL FLOW IS… We use if…else statements and logical operators to evaluate conditions and fork code execution. Which path should we take?
  • 35. CODE FOR ABOVE EXAMPLE var d, hours, minutes, time, message; // Get the current time’s hour and minute components d = new Date(); hours = d.getHours(); minutes = d.getMinutes(); // Make sure the hour is a double digit string if (hours < 10) { hours = “0” + hours; // converts hours to string } else { hours = hours.toString(); } //Make sure the minutes are a double digit string if (minutes < 10) { minutes = “0” + minutes; // converts minutes to string } else { minutes = minutes.toString(); } // Concatenate hours and minutes into a quadruple digit number representing the time in 24-hour format time = Number(hours + minutes); if (time >= 0000 && time < 1200) { message = “Good morning!”; } else if (time >= 1200 && time < 1700) { message = “Good afternoon!”; } else if (time >= 1700 && time < 2100) { message = “Good evening!”; } else if (time >= 2100 && time <=2359) { message = “Good night!”; } alert(message);
  • 36. WITH TERNARY OPERATOR var d, hours, minutes, time, message; // Get the current time’s hour and minute components d = new Date(); hours = d.getHours(); minutes = d.getMinutes(); // Make sure the hour is a double digit string hours = (hours < 10) ? “0” + hours : hours.toString(); // Make sure the minutes are a double digit string minutes = (minutes < 10) ? “0” + minutes : minutes.toString(); // Concatenate hours and minutes into a quadruple digit number representing the time in 24-hour format time = Number(hours + minutes); message = (time >= 0000 && time < 1200) ? “Good morning!” : (time >= 1200 && time < 1700) ? “Good afternoon!” : (time >= 1700 && time < 2100) ? “Good evening!” : (time >= 2100 && time <=2359) ? “Good night!”; alert(message); Ternary Operator = shortened if…else condition ? expression1 : expression2;
  • 37. PROJECT 1.0 Create a Task Manager Make a .js file and add this code var task1, task2, task3; task1 = “Pay phone bill”; task2 = “Write best-selling novel”; task3 = “Walk the dog”;