Web Site Design and Development JavaScript

Similar documents
CGS 3066: Spring 2015 JavaScript Reference

CSC Web Programming. Introduction to JavaScript

JavaScript CS 4640 Programming Languages for Web Applications

JavaScript CS 4640 Programming Languages for Web Applications

Background. Javascript is not related to Java in anyway other than trying to get some free publicity

Chapter 3 - Simple JavaScript - Programming Basics. Lesson 1 - JavaScript: What is it and what does it look like?

Variables and Typing

JavaScript I Language Basics

CSCE 120: Learning To Code

COMS 469: Interactive Media II

Client-Side Web Technologies. JavaScript Part I

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

CHIL CSS HTML Integrated Language

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

Visual C# Instructor s Manual Table of Contents

JavaScript: More Syntax

egrapher Language Reference Manual

Chapter 17. Fundamental Concepts Expressed in JavaScript

Java+- Language Reference Manual

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Full file at

3 The Building Blocks: Data Types, Literals, and Variables

Web Programming and Design. MPT Junior Cycle Tutor: Tamara Demonstrators: Aaron, Marion, Hugh

String Computation Program

What is PHP? [1] Figure 1 [1]

C++ Programming: From Problem Analysis to Program Design, Third Edition

PHP by Pearson Education, Inc. All Rights Reserved.

A.A. 2008/09. Why introduce JavaScript. G. Cecchetti Internet Software Technologies

Language Reference Manual simplicity

UNIT- 3 Introduction to C++

Princess Nourah bint Abdulrahman University. Computer Sciences Department

JME Language Reference Manual

Overview: Programming Concepts. Programming Concepts. Names, Values, And Variables

Overview: Programming Concepts. Programming Concepts. Chapter 18: Get With the Program: Fundamental Concepts Expressed in JavaScript

JavaScript. History. Adding JavaScript to a page. CS144: Web Applications

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

JavaScript: The Basics

Accelerating Information Technology Innovation

Information Science 1

Introduction to Visual Basic and Visual C++ Arithmetic Expression. Arithmetic Expression. Using Arithmetic Expression. Lesson 4.

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

COMS 469: Interactive Media II

Objectives. In this chapter, you will:

Sprite an animation manipulation language Language Reference Manual

GOLD Language Reference Manual

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Our Strategy for Learning Fortran 90

JavaScript. History. Adding JavaScript to a page. CS144: Web Applications

Ordinary Differential Equation Solver Language (ODESL) Reference Manual

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

Fundamental of Programming (C)

This tutorial will teach you about operators. Operators are symbols that are used to represent an actions used in programming.

Course Outline. Introduction to java

Cellular Automata Language (CAL) Language Reference Manual

GraphQuil Language Reference Manual COMS W4115

C: How to Program. Week /Mar/05

WEEK 4 OPERATORS, EXPRESSIONS AND STATEMENTS

Course 2320 Supplementary Materials. Modern JavaScript Best Practices

Chapter 2 Working with Data Types and Operators

Such JavaScript Very Wow

COMS W4115 Programming Languages & Translators GIRAPHE. Language Reference Manual

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

COMP519 Web Programming Lecture 11: JavaScript (Part 2) Handouts

Web Application Development (WAD) V th Sem BBAITM(Unit-1) By: Binit Patel

Introduction to C# Applications

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Chapter 2 - Introduction to C Programming

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

BASIC ELEMENTS OF A COMPUTER PROGRAM

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

CT 229. Java Syntax 26/09/2006 CT229

Chapter 2: Using Data

JavaScript Basics. The Big Picture

COMP1730/COMP6730 Programming for Scientists. Data: Values, types and expressions.

Information Science 1

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

CSCI 1061U Programming Workshop 2. C++ Basics

Lecture 2: Variables and Operators. AITI Nigeria Summer 2012 University of Lagos.

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Working with JavaScript

Introduction to C Programming

GridLang: Grid Based Game Development Language Language Reference Manual. Programming Language and Translators - Spring 2017 Prof.

ECON 502 INTRODUCTION TO MATLAB Nov 9, 2007 TA: Murat Koyuncu

JavaScript Functions, Objects and Array

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

MatchaScript: Language Reference Manual Programming Languages & Translators Spring 2017

Object Oriented Programming with Java

SPARK-PL: Introduction

CS313D: ADVANCED PROGRAMMING LANGUAGE

PHPoC vs PHP > Overview. Overview

BoredGames Language Reference Manual A Language for Board Games. Brandon Kessler (bpk2107) and Kristen Wise (kew2132)

Lesson 3: Basic Programming Concepts

Python Programming Exercises 1

JScript Reference. Contents

Language Reference Manual

Data Types and the main Function

Transcription:

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

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 4

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 5

Code as child example <script> console.log("hello World!"); </script> 6

Code in a separate file script.js console.log("hello World!"); In HTML file just before closing body tag <script src="script.js"></script> 7

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 8

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

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 10

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 11

Variable examples let num; let name = "Adam"; let live = true; let increment = 2; let useraddress; num = 4; useraddress = "123 Alphabet Rd"; 12

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

Numbers Numbers are numerical values between -(253-1) and (2 53 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) 14

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

Booleans Booleans are the values true and false Examples result = true; passed = false; 16

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 17

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

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

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

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 21

Math Examples result = 2 + 5; result = a / 13; result = (a ** 2 + b ** 2) / (c ** 2); incr++; ++incr; 22

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 23

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 24

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 25

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

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 27

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 28

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 29

Comparison Operator Examples 2 < 4 a === undefined color == "red" count >= 10 answer!== false 30

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

Logical Operator Examples answer > 5 && answer <= 10!booleanResponse color == "blue" color == "green" 32

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. 33

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

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 35

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 36

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 37

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 38

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

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 40

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

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 42

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 43

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 44

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 45

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 46

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

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 48

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

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 as for(iterator; finishcondition; updateiterator) { //some code to execute } 50

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 51

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 52

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

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 54

Comment Examples //this is a single line comment let x = 0; //another single line comment /* A multiple line comment */ //console.log("commented out code"); 55