chapter 8 introduction to javascript - skkumonet.skku.edu/wp-content/uploads/2019/10/chapter...loops...
TRANSCRIPT
Computer Networking Networking Laboratory 1/34
Sungkyunkwan University
Copyright 2000-2012 Networking LaboratoryCopyright 2000-2018 Networking Laboratory
Chapter 8
Introduction to JavaScript
Prepared by DT. Binh and H. Choo
Computer Networking Networking Laboratory 2/34
What We've Learned So Far
How to write content for a webpage using HTML
How to add styles to a webpage using CSS and linking a CSS file to
an HTML file
How to inspect the HTML and CSS of web pages in the browser
Computer Networking Networking Laboratory 3/34
Today: JavaScript
Now that we know how to add content and styles to a web page, let's
explore how to add responsive behavior
This lecture we'll cover the basics of the JavaScript language:
JavaScript vs. Java comparisons
Syntax and types
Loops and functions
Events (basics) and form elements
Later we'll use these building blocks to learn how to dynamically
update what you see on a web page in response to clicks, text input,
timers, etc.
Computer Networking Networking Laboratory 4/34
Terminology: Client-Side Scripting
Client-side script: Code runs in browser after page is sent back from server. Often, this code manipulates the page or responds to user actions.
Computer Networking Networking Laboratory 5/34
What is JavaScript?
A lightweight programming language ("scripting language")
Created in 1995 (over 10 days) by Brendan Elch (originally called
Mocha then LiveScript)
Used to make web pages interactive:
Insert dynamic text into HTML (ex: username)
React to events (ex: page load, user's mouse click)
Get information about a user's computer (ex: what browser they are using)
Perform calculations on user's computer (ex: form validation)
A web standard (but not supported identically by all browsers)
NOT related to Java other than name and some syntactic similarities...
Can be used in the browser, Adobe Acrobat, Adobe Photoshop,
embedded computers, the Unix terminal, etc. (we will be using it in the
browser)
Computer Networking Networking Laboratory 6/34
JavaScript vs. Java
Interpreted, not compiled
More relaxed syntax and rules
Fewer and "looser" data types
Variables don't need to be declared
Errors often silent (few exceptions)
JavaScript's key construct is the function rather than the object/class
"first-class" functions are used in many situations
Contained within a web page and integrates with its HTML/CSS
content
Computer Networking Networking Laboratory 7/34
Linking to a JavaScript file: <script>
The script tag should be placed in the HTML page's head
Script code is stored in a separate .js file
JS code can be placed directly in the HTML file's body or head (like
CSS)
This is bad style though: You should always separate content,
presentation, and behavior
Computer Networking Networking Laboratory 8/34
Our First JavaScript Statement: alert
A JS command that pops up a dialog box with a message
Syntax:
Example:
Computer Networking Networking Laboratory 9/34
Variables and types
Syntax:
Example:
Variables are declared with the let keyword (case-sensitive). You may also see
var used instead of let - this is an older convention, and you should use let in this
class.
Types are not specified, but JS does have types ("loosely-typed")
• Number, Boolean, String, Array, Object, Function, Null, Undefined
• Can find out a variable's type by calling typeof
• Note: Type conversion isn't always what you expect...
Computer Networking Networking Laboratory 10/34
Number type
Integers and real numbers are the same type (no int vs. double)
Same operators: + - * / % ++ -- = += -= *= /= %=
Similar precedence to Java
Many operators auto-convert types: "2" * 3 is 6
Computer Networking Networking Laboratory 11/34
String type
Methods: charAt, charCodeAt, fromCharCode, indexOf,
lastIndexOf, replace, split, substring, toLowerCase, toUpperCase
charAt returns a one-letter String (there is no char type)
length is a property (not a method, as it is in Java)
Concatenation with +: 1 + 1 is 2, but "1" + 1 is "11"
Computer Networking Networking Laboratory 12/34
More about Strings
Escape sequences behave as in Java: \' \" \& \n \t \\
To convert between numbers and Strings:
let count = 10; // 10
let stringedCount = "" + count; // "10"
let helloCount = count + " hello!"; // "10 hello!"
let magicNum = parseInt("42 is the answer"); // 42
let mystery = parseFloat("Am I a number?"); // NaN
To access characters of a String s, use s[index] or s.charAt(index):
let firstLetter = helloCount[0]; // "1"
let fourthLetter = helloCount.charAt(3); // “h"
let lastLetter = helloCount.charAt(helloCount.length - 1); // "!"
Computer Networking Networking Laboratory 13/34
Comments (same as Java)
Identical to Java's comment syntax
Recall: 3 comment syntaxes
HTML: <!-- comment -->
CSS/Java/JS: /* comment */
Java/JS: // comment
Computer Networking Networking Laboratory 14/34
for loop (same as Java)
Computer Networking Networking Laboratory 15/34
Math object
Methods: abs, ceil, cos, floor, log, max, min, pow, random, round, sin,
sqrt, tan
Properties: E, PI
Computer Networking Networking Laboratory 16/34
Logical Operators
Relational: > < >= <=
Logical: && || !
Equality: == != === !==
Most logical operators automatically convert types. These are all true:
5 < "7"
42 == 42.0
"5.0" == 5
The === and !== are strict equality tests; checks both type and value: "5.0"
=== 5 is false
Computer Networking Networking Laboratory 17/34
Boolean Type
Any value can be used as a Boolean
"falsey" values: 0, 0.0, NaN, "", null, and undefined
"truthy" values: anything else
Converting a value into a Boolean explicitly:
Computer Networking Networking Laboratory 18/34
Special Values: null and undefined
undefined: has not been declared, does not exist
null: exists, but was specifically assigned an empty or null value
Computer Networking Networking Laboratory 19/34
if/else Statements (same as Java)
Identical structure to Java's if/else statements
JavaScript allows almost anything as a condition
Computer Networking Networking Laboratory 20/34
while loops (same as Java)
break and continue keywords also behave as in Java but do not use them in
this class!
Computer Networking Networking Laboratory 21/34
Arrays
Two ways to initialize an array
length property (grows as needed when elements are added)
Computer Networking Networking Laboratory 22/34
Array methods
Array serves as many data structures: list, queue, stack, ...
Methods: concat, join, pop, push, reverse, shift, slice, sort, splice, toString, unshift
• push and pop add/remove from back
• shift and unshift add/remove from front
• shift return the element that is removed
• pop return the first element (not removed)
Computer Networking Networking Laboratory 23/34
Splitting strings: split and join
• split breaks apart a String into an array using a delimiter
• Can also be used with regular expressions surrounded by /:
▪ let a = s.split(/[ \t]+/);
• join merges an array into a single String, placing a delimiter between them
Computer Networking Networking Laboratory 24/34
Defining functions
The above could be the contents of example.js linked to our HTML page
Statements placed into functions can be evaluated in response to user events
Computer Networking Networking Laboratory 25/34
Event-Driven Programming
Unlike Java programs, JS programs have no main; they respond to user actions
called events
Computer Networking Networking Laboratory 26/34
Event Handlers
JavaScript functions can be set as event handlers
When you interact with the element, the function will execute
onclick is just one of many event HTML attributes we'll use
Computer Networking Networking Laboratory 27/34
Buttons: <button>
Button's text appears inside tag; can also contain images
To make a responsive button or other UI control:
• Choose the control (e.g., button) and event (e.g., mouse click) of interest
• Write a JavaScript function to run when the event occurs
• Attach the function to the event on the control
Computer Networking Networking Laboratory 28/34
Accessing an Element:
document.getElementById returns the DOM object for an element with a given
id (note that you omit the # when giving an id)
Computer Networking Networking Laboratory 29/34
document.getElementById: An Example
Practice on your computer!
Computer Networking Networking Laboratory 30/34
So... how can JavaScript be useful on a
webpage?
A common use for JavaScript on webpages is for event-handling and
form validation. To use form validation, we need to learn about a few
more HTML tags...
Computer Networking Networking Laboratory 31/34
Form Elements: <input>
Practice on your computer
name attribute specifies name of query parameter to pass to server
type can be button, checkbox, file, hidden, password, radio, reset, submit,
text, ...
value attribute specifies control's initial text
Computer Networking Networking Laboratory 32/34
<input> text fields
Practice on your computer!
input attributes: disabled, maxLength, readonly, size, value
size attribute controls onscreen width of text field
maxlength limits how many characters the user is able to type into the field
Computer Networking Networking Laboratory 33/34
Form Elements: Text boxes: <textarea>
Practice on your computer!
Initial text is placed inside textarea tag (optional)
Required rows and cols attributes specify height/width in characters
optional readonly attribute means text cannot be modified
Computer Networking Networking Laboratory 34/34
Resources and Tips
Review programming basics: using variables, arrays, loops, if-stateme
nts, and functions
Go over some JavaScript tutorials - there are many great ones!
https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_
web/JavaScript_basics
https://www.codecademy.com/learn/introduction-to-javascript
Practice! We now have JavaScript problems on Practice-It (80+ proble
ms) and its sister site CodeStepByStep (200+ problems).
Check out cool examples of JavaScript on the web!
Dennis Music Video
Robby Leonardi Mario-style Resume
Species in Pieces
Rainbow Worm
OMFGDOGS