Web Site Design and Development JavaScript CS 0134 Fall 2018 Tues - - PowerPoint PPT Presentation

web site design and development javascript
SMART_READER_LITE
LIVE PREVIEW

Web Site Design and Development JavaScript CS 0134 Fall 2018 Tues - - PowerPoint PPT Presentation

Web Site Design and Development JavaScript CS 0134 Fall 2018 Tues and Thurs 1:00 2:15PM JavaScript JavaScript is a programming language that was designed to run in your web browser. 2 Some Definitions Script A script is a


slide-1
SLIDE 1

Web Site Design and Development JavaScript

CS 0134 Fall 2018 Tues and Thurs 1:00 – 2:15PM

slide-2
SLIDE 2

2

JavaScript

  • JavaScript is a programming language that

was designed to run in your web browser.

slide-3
SLIDE 3

3

Some Definitions

  • Script

– A script is a collection of code that is used to solve some problem

  • Code

– Code is a term that refers to the statements and blocks written in

JavaScript that make up a script

  • Statement

– A statement is an instruction for a computer to process

  • Block

– A block is a group of statements surrounded by {}

slide-4
SLIDE 4

4

Script element

  • The script element is used to define client-side

scripts for a web page

  • In HTML5, by default, the browser assumes any

scripts defined by the script element to be written in JavaScript

  • You can define JavaScript with the script element in

two ways

– Place the code inside the script element as a child – Use the src attribute to point to a separate file that contains

the code

slide-5
SLIDE 5

5

Script element continued

  • While not required, it is beneficial to place

the script element as the last child before the body’s closing tag as this speeds up the loading of your web pages

  • Like CSS, it is advisable to keep your

JavaScript in a separate file

slide-6
SLIDE 6

6

Code as child example

<script> console.log("Hello World!"); </script>

slide-7
SLIDE 7

7

Code in a separate file

  • script.js

console.log("Hello World!");

  • In HTML file just before closing body tag

<script src="script.js"></script>

slide-8
SLIDE 8

8

The console

  • Modern desktop web browsers come with a

console

  • The console lets you see messages,

warnings and errors related to your web page

  • You open the console with Ctrl+Shift+J

(Cmd+Option+J) in Chrome and Ctrl+Shift+K (Cmd+Option+K) in Firefox

slide-9
SLIDE 9

9

console.log(msg)

  • You can use console.log(msg) to write msg

to the console.

  • This is useful because you may want to

have your script print out helpful messages while you are developing it

  • Example

console.log("Hello World!");

slide-10
SLIDE 10

10

Variables

  • Variables are used to store data
  • To define a variable you use the keyword let followed

by a variable name

  • Naming variables

– Names are made up of letters, numbers and underscores. – The first character of a name must be a letter or underscore – Do not use one of the language's keywords as a variable name

as this can cause confusion, you can find a list here, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe rence/Lexical_grammar#Keywords

slide-11
SLIDE 11

11

Variables continued

  • You can assign a value to a variable using the form

"variable = value"

  • You can do this assignment both when you define

the variable as well as further on in the script

  • JavaScript variables have scope, more on that later
  • JavaScript is a language that uses dynamic typing.

What this means is that you can assign any value to a variable and change the type of the value throughout the script

slide-12
SLIDE 12

12

Variable examples

  • let num;
  • let name = "Adam";
  • let live = true;
  • let increment = 2;
  • let userAddress;
  • num = 4;
  • userAddress = "123 Alphabet Rd";
slide-13
SLIDE 13

13

Types of data

  • JavaScript has the following types of data

that we can work with

– Numbers – Strings – Booleans – Null – Undefined – Arrays

slide-14
SLIDE 14

14

Numbers

  • Numbers are numerical values between -(253 -

1) and (253 – 1) (also known as - 9,007,199,254,740,991 and 9,007,199,254,740,991)

  • Numbers can be written as integers, decimals

and scientific notation

  • In addition to explicit numbers, a number can

be represented with

  • Infinity, +Infinity and NaN (not a number)
slide-15
SLIDE 15

15

Strings

  • A string is a set of characters surrounded

by quotations

  • Strings are typically words and sentences
  • You can join two strings together by using

the plus sign

  • Example

– name = "Adam";

console.log("Hello, my name is " + name);

slide-16
SLIDE 16

16

Booleans

  • Booleans are the values true and false
  • Examples

– result = true; – passed = false;

slide-17
SLIDE 17

17

Null and undefined

  • null represents no value
  • Undefined happens when a variable has

been declared but no value has been defined

  • Examples

– result = null; – let a;

console.log(a); //will print undefined

slide-18
SLIDE 18

18

Arrays

  • Arrays are an ordered collection of data
  • Arrays can consist of data in any type,

including other arrays

  • You define an array with a series of values

separated by commas all surrounded by brackets

  • Example

– a = [1, 2, 3, 4];

slide-19
SLIDE 19

19

Arrays continued

  • You can access a value in an array by using the

arrays variable name followed by the values index in brackets

  • An array index is a numerical value that points to

where the value exists in the array; The index for the first value in an array is 0 and increments for every value in the array

  • Example

– a = [1, 2, 3, 4];

console.log(a[0]);

slide-20
SLIDE 20

20

Math

  • Math in JavaScript uses the follow operators

– Addition: + – Subtraction: - – Multiplication: * – Division: / – Exponentiation: ** (does not work in IE) – Remainder: % – Increment by 1: ++ – Decrement by 1: --

slide-21
SLIDE 21

21

Math Continued

  • You can also use parenthesis
  • Math in JavaScript will follow the order of
  • perations from algebra
  • If you have a variable whose value is not a number

and you try to do math on it, JavaScript will try to convert the variable to a number before doing the math.*

* This will work unless one of the operands is a string and you are doing addition. In this case, the other operand is turned into a string and the values are concatenated

slide-22
SLIDE 22

22

Math Examples

  • result = 2 + 5;
  • result = a / 13;
  • result = (a ** 2 + b ** 2) / (c ** 2);
  • incr++;
  • ++incr;
slide-23
SLIDE 23

23

Assignment Operators

  • In addition to using an equal sign to assign a value to a

variable, you can use one of the following

– += – -= – *= – /= – **= – %=

  • What these assignment operators do is perform a

mathematical equation using the variable is the first

  • perand and assigns the result to the variable
slide-24
SLIDE 24

24

Assignment Operator Examples

  • let x = 5;

x += 3;

  • The above can also be written as

– let x = 5;

x = x + 3;

  • In both cases, the variable x has the value
  • f 8 after the assignment
slide-25
SLIDE 25

25

A note on semicolons

  • As you have seen from the examples, every

statement ends with a semicolon

  • You can leave the semicolon off of a statement in

certain situations but not others, thus you may see statements online without semicolons

  • I recommend that you always end your statements

with a semicolon because having the semicolon there when it can be omitted does not hurt but missing one where it cannot be omitted will cause errors

slide-26
SLIDE 26

26

If statement

  • The if statement gives us the ability to

execute code based on if something is true

  • r false
  • The format is

if(condition) { execute if true } else { execute if false }

slide-27
SLIDE 27

27

The if condition

  • The if condition can be anything that will

have a final value of true or false

  • This is often written in the form of a

comparison between two values but can also be the value of a particular variable or the result of a function, more on functions later

slide-28
SLIDE 28

28

Comparison Operators

  • You can compare values in JavaScript using the

following

– == (Equality): two values are equal, JavaScript will attempt to

convert the values to the same type to do the comparison

– != (Inequality): two values are not equal, JavaScript will attempt

to convert the values to the same type to do the comparison

– === (Strict Equality): two values are equal and the same type – !== (Strict Inequality): two values are not the same and/or not

the same type

slide-29
SLIDE 29

29

Comparison Operators Continued

– > (greater than) – < (less than) – >= (greater than or equal to) – <= (less than or equal to) – The last four comparison operators will try to to

get numeric values from both operands before doing the comparison

slide-30
SLIDE 30

30

Comparison Operator Examples

  • 2 < 4
  • a === undefined
  • color == "red"
  • count >= 10
  • answer !== false
slide-31
SLIDE 31

31

Logical Operators

  • In addition to being able to have a single

variable, comparison of two values or result of a function in our conditions, we can also group these into larger conditions

  • We group these using logical operators, those
  • perators are

– && (and) – || (or) – ! (not)

slide-32
SLIDE 32

32

Logical Operator Examples

  • answer > 5 && answer <= 10
  • !booleanResponse
  • color == "blue" || color == "green"
slide-33
SLIDE 33

33

Else if

  • You can also stitch together a series of if

statements using else if.

  • This works by evaluating the condition of

the first if, if the condition is false, it goes to the else if and evaluates the condition for it. It continues in this fashion until an else if condition is true or the final else is found if it exists.

slide-34
SLIDE 34

34

If example

if (color == "red" || color == "orange") { console.log("warm color found"); } else if (color == "blue" || color == "green") { console.log("cool color found"); } else { console.log("color of unknown type found: " + color); }

slide-35
SLIDE 35

35

Functions

  • A function is a block of code that we can

invoke to perform a particular task

  • There are several benefits to using functions

– Functions allow you to keep from writing the same

code multiple times

– Functions break your code into chunks that can be

easier to maintain

– Functions allow us to write code that reacts to events

that happen on a web page

slide-36
SLIDE 36

36

Functions continued

  • Functions are defined with the function keyword

function name([param][, param][…]) { The code to execute }

– Name is a name for the function. Each function in a

script will have a unique name.

– The params are 0 or more parameters your function

  • uses. Parameters are bits of information that will be

passed into the function that will have an affect on the result of the function

slide-37
SLIDE 37

37

Functions continued

  • There is no limit on the code that can be

placed inside of a function. That is, any valid JavaScript, including calls to other functions is allowed

  • The code inside a function should always

give the same result when given the same input

slide-38
SLIDE 38

38

Return statement

  • The return statement is used to return a

value from a function to where the function was called

  • When the return statement is used, no more

statements in the function are executed

  • By default a function without a return

statement will return undefined to where the function was called

slide-39
SLIDE 39

39

Function examples

  • function add(x, y) {

return x + y; }

  • function colorTemp(color) {

if (color == "red" || color == "orange") { return "warm"; } else if (color == "blue" || color == "green") { return "cool"; } else { return null; } }

slide-40
SLIDE 40

40

Calling a function

  • You call a function by using its name followed by

parenthesis

  • If the function has parameters, you can pass values

to those parameters as arguments placed inside the parenthesis

  • When the function returns, the return value will be

wherever your call is, this means if your call is, for example, in the condition of an if statement, the returned value will be used in determining if the condition is true or false

slide-41
SLIDE 41

41

Calling a function continued

  • You can capture the result of a function call

for use later in your script by assigning the call to a variable

  • Examples

– notifyUser(); – let result = colorTemp("blue"); – if(add(2, 3) == 5) {

console.log("We found five!"); }

slide-42
SLIDE 42

42

Scope

  • As mentioned earlier, variables have scope. Scope

defines where a variable can be accessed

  • Variables defined in your script but outside a

function have global scope. What this means is that the variable can be accessed from anywhere in the script

  • Variables defined in a function, as well as the

parameters, have local scope. This means that the variables are only accessible from within the function

slide-43
SLIDE 43

43

Global Scope Example

  • let color = "blue";

function f() { console.log(color); } f();

  • This example will print blue to the console

because color is defined in the global scope and thus accessible inside the function

slide-44
SLIDE 44

44

Local Scope Example

  • function f() {

let num = 3; } f(); console.log(num);

  • This example will error because num was

defined in the function f's local scope and is therefore not accessible from outside the function

slide-45
SLIDE 45

45

Re-using a global variables name in a function

  • You can define a variable within a function

that uses the same name as a variable defined globally

  • This gives you a new variable with local

scope

  • This does not affect the value of the global

variable

slide-46
SLIDE 46

46

Re-use example

  • let num = 2;

console.log("Value of num before function is " + num); function f() { let num = 3; console.log("Value of num inside function is " + num); } f(); console.log("Value of num after function is " + num);

  • This exmaple will have the following output:

Value of num before function is 2 Value of num inside function is 3 Value of num after function is 2

slide-47
SLIDE 47

47

Attaching a JavaScript function to HTML

  • To attach a JavaScript function to HTML, you use

the onclick attribute

  • The value of the onclick attribute will be a

JavaScript snippet that calls the function you wish to call

  • When a user clicks on the element that has the
  • nclick attribute, the function will be called
  • Example

– <button onclick="alert('You clicked me!')">Button</button>

slide-48
SLIDE 48

48

Objects

  • An object is a collection of variables (known as

properties) and functions (known as methods)

  • An object is defined by a comma separated set
  • f "name:value" pairs inside of {}
  • You can access a property or method inside an
  • bject by using '.'
  • Within an object, you can access the objects

properties and methods by using the this keyword

slide-49
SLIDE 49

49

Object example

  • let dog = {

breed: "boxer", name: "Jasper", hungry: true, feed: function() { this.hungry = false; } } console.log(dog.name); console.log(dog.hungry); dog.feed(); console.log(dog.hungry);

slide-50
SLIDE 50

50

For loops

  • A for loop will execute a block of code a

specified number of times

  • For loops are convenient for executing a block
  • f code for every element in an array
  • A for loop is written as

for(iterator; finishCondition; updateIterator) { //some code to execute }

slide-51
SLIDE 51

51

For loop examples

  • for(let x = 0; x < 10; x++) {

console.log(x); }

  • let names = ["Daisy", "Spike", "Rover"];

for(let x = 0; x < names.length; x++) { console.log(names[x]); }

  • names.length is the number of items in an array. In

the example above, this is 3 since we have 3 names

slide-52
SLIDE 52

52

Regular Expressions

  • Just like with HTML5, regular expressions can be used

to test if a string matches a pattern

  • With JavaScript, however, you can also test parts of

strings for the pattern, collect data from those matches into a variable and replace the contents in your string. For this class, we will stick to testing

  • The JavaScript regular expression uses the same

pattern syntax as HTML5. A full reference is available here, https://www.w3schools.com/js/js_regexp.asp

slide-53
SLIDE 53

53

Regular expressions continued

  • A regular expression is defined as a pattern

surrounded by //

– Example

let phone_number = /^\d{3}-\d{3}\-\d{4}$/;

  • You can then test that a string matches the pattern

with the test() method. This method will return true if the pattern matches and false if it does not

– Example

phone_number.test("724-555-5555");

slide-54
SLIDE 54

54

Comments

  • Like HTML and CSS, JavaScript has the concept of

comments

  • Some comments have already been seen in these

slides

  • To do a single line comment, you use // followed by

the comment you want to make. Everything after //

  • n a line is ignored when the script is run
  • To do a multiline comment, you use /* followed by

your comment. To end the comment, you use */, Everything between /* and */ is ignored

slide-55
SLIDE 55

55

Comment Examples

  • //this is a single line comment

let x = 0; //another single line comment

  • /*

A multiple line comment */

  • //console.log("commented out code");