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 - - 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
2
JavaScript
- JavaScript is a programming language that
was designed to run in your web browser.
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 {}
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
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
6
Code as child example
<script> console.log("Hello World!"); </script>
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>
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
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!");
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
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
12
Variable examples
- let num;
- let name = "Adam";
- let live = true;
- let increment = 2;
- let userAddress;
- num = 4;
- userAddress = "123 Alphabet Rd";
13
Types of data
- JavaScript has the following types of data
that we can work with
– Numbers – Strings – Booleans – Null – Undefined – Arrays
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)
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);
16
Booleans
- Booleans are the values true and false
- Examples
– result = true; – passed = false;
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
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];
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]);
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: --
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
22
Math Examples
- result = 2 + 5;
- result = a / 13;
- result = (a ** 2 + b ** 2) / (c ** 2);
- incr++;
- ++incr;
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
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
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
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 }
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
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
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
30
Comparison Operator Examples
- 2 < 4
- a === undefined
- color == "red"
- count >= 10
- answer !== false
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)
32
Logical Operator Examples
- answer > 5 && answer <= 10
- !booleanResponse
- color == "blue" || color == "green"
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.
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); }
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
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
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
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
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; } }
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
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!"); }
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
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
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
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
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
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>
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
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);
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 }
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
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
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");
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
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");