55
JavaScript CS 0134

JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

  • Upload
    others

  • View
    6

  • Download
    0

Embed Size (px)

Citation preview

Page 1: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

JavaScript

CS 0134

Page 2: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

2

JavaScript

● JavaScript is a programming language that was designed to run in your web browser.

Page 3: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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 {}

Page 4: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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

Page 5: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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

Page 6: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

6

Code as child example

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

</script>

Page 7: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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>

Page 8: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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+K (Cmd+Option+K) in Firefox

Page 9: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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!");

Page 10: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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/Reference/Lexical_grammar#Keywords

Page 11: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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

Page 12: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

12

Variable examples

● let num;● let name = "Adam";● let live = true;● let increment = 2;● let userAddress;● num = 4;● userAddress = "123 Alphabet Rd";

Page 13: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

13

Types of data

● JavaScript has the following types of data that we can work with– Numbers– Strings– Booleans– Null– Undefined– Arrays

Page 14: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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)

Page 15: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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);

Page 16: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

16

Booleans

● Booleans are the values true and false● Examples

– result = true;– passed = false;

Page 17: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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

Page 18: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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];

Page 19: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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]);

Page 20: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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: --

Page 21: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

21

Math Continued

● You can also use parenthesis● Math in JavaScript will follow the order of

operations 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

Page 22: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

22

Math Examples

● result = 2 + 5;● result = a / 13;● result = (a ** 2 + b ** 2) / (c ** 2);● incr++;● ++incr;

Page 23: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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 operand and assigns the result to the variable

Page 24: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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 of 8 after the assignment

Page 25: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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

Page 26: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

26

If statement

● The if statement gives us the ability to execute code based on if something is true or false

● The format is

if(condition) {execute if true

} else {execute if false

}

Page 27: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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

Page 28: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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

Page 29: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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

Page 30: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

30

Comparison Operator Examples

● 2 < 4● a === undefined● color == "red"● count >= 10● answer !== false

Page 31: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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 operators are– && (and)– || (or)– ! (not)

Page 32: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

32

Logical Operator Examples

● answer > 5 && answer <= 10● !booleanResponse● color == "blue" || color == "green"

Page 33: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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.

Page 34: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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);}

Page 35: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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

Page 36: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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

Page 37: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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

Page 38: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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

Page 39: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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;}

}

Page 40: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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

Page 41: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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!");}

Page 42: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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

Page 43: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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

Page 44: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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

Page 45: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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

Page 46: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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 2Value of num inside function is 3Value of num after function is 2

Page 47: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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 onclick attribute, the function will be called

● Example– <button onclick="alert('You clicked

me!')">Button</button>

Page 48: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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 of "name:value" pairs inside of {}

● You can access a property or method inside an object by using '.'

● Within an object, you can access the objects properties and methods by using the this keyword

Page 49: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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);

Page 50: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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 of code for every element in an array

● A for loop is written asfor(iterator; finishCondition; updateIterator) {

//some code to execute}

Page 51: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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

Page 52: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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

Page 53: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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");

Page 54: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

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 // on 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

Page 55: JavaScript - University of Pittsburghach54/teaching/cs0134-2194/slides/javascript.pdf · Arrays continued You can access a value in an array by using the arrays variable name followed

55

Comment Examples

● //this is a single line commentlet x = 0; //another single line comment

● /*Amultiplelinecomment*/

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