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

Similar documents
Working with JavaScript

CGS 3066: Spring 2015 JavaScript Reference

CSC Web Programming. Introduction to JavaScript

COMS 469: Interactive Media II

INFS 2150 Introduction to Web Development and e-commerce Technology. Programming with JavaScript

Objectives. Introduction to JavaScript. Introduction to JavaScript INFS Peter Y. Wu, RMU 1

Internet & World Wide Web How to Program, 5/e by Pearson Education, Inc. All Rights Reserved.

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

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

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

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0. L J Howell UX Software Ver. 1.0

Chapter 2: Functions and Control Structures

Chapter 2 Working with Data Types and Operators

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

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

Web Site Design and Development JavaScript

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

CMPT 100 : INTRODUCTION TO

JavaScript by Vetri. Creating a Programmable Web Page

JavaScript CS 4640 Programming Languages for Web Applications

egrapher Language Reference Manual

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Lesson 1: Writing Your First JavaScript

Programming Logic and Design Seventh Edition Chapter 2 Elements of High-Quality Programs

COSC 122 Computer Fluency. Iteration and Arrays. Dr. Ramon Lawrence University of British Columbia Okanagan

STUDENT LESSON A12 Iterations

Full file at

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Iteration and Arrays Dr. Abdallah Mohamed

Overview. Iteration 4 kinds of loops. Infinite Loops. for while do while foreach

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Repetition CSC 121 Fall 2014 Howard Rosenthal

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

JavaScript CS 4640 Programming Languages for Web Applications

8. Control statements

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

Lesson 3: Basic Programming Concepts

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Introduction to the Java Basics: Control Flow Statements

Dynamism and Detection

Chapter 2: Basic Elements of C++

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

Visual C# Instructor s Manual Table of Contents

Introduction to JavaScript

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

What is Java Script? Writing to The HTML Document. What Can JavaScript do? CMPT 165: Java Script

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Computer Programming I - Unit 5 Lecture page 1 of 14

COMP 202 Java in one week

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators

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

Lecture 14. Introduction to JavaScript. Mr. Mubashir Ali Lecturer (Dept. of Computer Science)

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

YOLOP Language Reference Manual

DEPARTMENT OF MATHS, MJ COLLEGE

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

COMP 202. Java in one week

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

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

CS 115 Lecture 4. More Python; testing software. Neil Moore

A JavaBean is a class file that stores Java code for a JSP

Chapter Goals. Contents LOOPS

Handout 9: Imperative Programs and State

Chapter 17. Fundamental Concepts Expressed in JavaScript

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

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

School of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn

OBJECT ORIENTED SIMULATION LANGUAGE. OOSimL Reference Manual - Part 1

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

PLT Fall Shoo. Language Reference Manual

Programming Languages Third Edition

Pace University. Fundamental Concepts of CS121 1

Coding Workshop. Learning to Program with an Arduino. Lecture Notes. Programming Introduction Values Assignment Arithmetic.

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Operators. Java operators are classified into three categories:

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 2. C++ Basics

CMPT 125: Lecture 3 Data and Expressions

STUDENT LESSON A5 Designing and Using Classes

Exercise 1 Using Boolean variables, incorporating JavaScript code into your HTML webpage and using the document object

Accelerating Information Technology Innovation

Princess Nourah bint Abdulrahman University. Computer Sciences Department

HTML5 and CSS3 More JavaScript Page 1

Text Input and Conditionals

Using Basic Formulas 4

JAVASCRIPT. sarojpandey.com.np/iroz. JavaScript

The PCAT Programming Language Reference Manual

9. MATHEMATICIANS ARE FOND OF COLLECTIONS

Java Primer 1: Types, Classes and Operators

JavaScript Functions, Objects and Array

Part II Composition of Functions

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

The SPL Programming Language Reference Manual

Java+- Language Reference Manual

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

Transcription:

Chapter 3 - Simple JavaScript - Programming Basics Lesson 1 - JavaScript: What is it and what does it look like? PP presentation JavaScript.ppt. Lab 3.1. Lesson 2 - JavaScript Comments, document.write(), and document.writeln() Like HTML, JavaScript supports comments. In fact, JS comments come in two forms: - JS line comments follow two forward slashes //. - JS block comments begin with /* and end with */. Example: JSCommentsWrite.html. Writing (printing) in JS is accomplished with the document.write() and document.writeln() methods. - The document object represents the contents of the browser s window. - We use the document object with the write() and the writeln() methods. - The write() and writeln() methods take a text string as an argument. The argument is enclosed in quotation marks. - writeln() adds a carriage return after its text argument. write() does not. Example: JSCommentsWrite.html. Note the <PRE>...</PRE> tags. Lab 3.2. Lesson 3 - Variable Assignments and Expressions variable - a value stored in a computer. A variable can be thought of as a container that holds things like numbers and letters. The particular value a variable stores can change. That s why it s called a variable! The notion of a variable in computing is exactly the same as variable in mathematics. For example, if x = 4, then 3 + x = 7, and so on. In a program, you should give variables names which suggest what they stand for. Using simply x for a variable isn t very descriptive. Instead, use something like totalcost or total_cost There are some rules and conventions you need to observe when naming variables. - Variable names must begin with a letter or a $ or an _. In particular, a variable name CANNOT begin with a number. - A common practice is to use words to describe the variable with either an _ separating the words or the first word starting in lower case and subsequent words capitalized. - Certain words are reserved and may not be used as names of variables. - Recall that JavaScript is case sensitive. paycheck and PAYCHECK and Paycheck and paycheck and PaYcHeCk are all different variables. - Variable names may not contain spaces.

Variables are declared by using the var keyword. For example, var paycheck = 1200; In addition to being a number, a variable can also be a sequence of characters or a string. For example, var myname = "Jim"; (Note the quotation marks.) data type - the type of information a variable carries. JavaScript has four data types: - number - a whole number or a decimal. - logical or boolean - the logical values true or false. The name boolean comes from George Boole, a 19th century mathematician who developed some of the theories of mathematical logic. - string - text. - null - an empty value. JavaScript is a loosely typed programming language in the sense that you do not (and are not allowed to) declare variables by type. Moreover, the type of a variable can change throughout a program. On the other hand, Java is a strongly typed programming language. Examples: NumberVariables.html and StringVariables.html. Be sure to read the discussion in Lesson 3 about operators and expressions. A list of basic operators with examples is given in the table. expression - a combination of values, variables, and operators which can be evaluated. An operator can be classified by the type of operation it performs. arithmetic operators - the operators +, -, *, /, % used for ordinary arithmetic. comparison operators - the operators <, <=, >, >=, == used to compare two quantities. Note that == and not the assignment operator = is used to test for equality. assignment operators - operators used to assign values to variables. There are several assignment operators, but the only one we use is =. - In programming, you have to understand that = is an assignment operator. - For example, a statement such as i = i + 1; is mathematically incorrect if viewed as an equation, but it is a correct programming statement. What happens is that 1 is added to the current value of i and the result is assigned as the new value of i. - For another example, the statements var x = 5, y = 8; x = x + y; result in x having the value 13. logical operators - next lesson. Lab 3.3. Lab 3.4.

Lesson 4 - Control Structures Up to now, the flow control in a JavaScript program has been simple; actions were performed in the order they were written down. We now look at how to write programs with more complicated flow control. The ability to alter the flow control adds a whole new dimension to the types of programs you can write. if and if-else Statements In programs, just as in everyday life, things can sometimes go in one of two different ways. For example, if you have money in a checking account, your bank might pay you a little interest. On the other hand, if your checking account is overdrawn, your bank might charge you a penalty that will make your negative balance even more negative. This could be reflected in the bank s accounting program by the following if-else statement: balance is a variable containing your checking-account balance. INTEREST_RATE is a constant equal to the bank s interest rate. OVERDRAWN_PENALTY is a constant equal to the bank s overdrawn penalty. if (balance >= 0) balance = balance + (INTEREST_RATE * balance)/12; else balance = balance - OVERDRAWN_PENALTY; The meaning of this if-else statement is just the meaning it would have if it was read as an English sentence. When your program executes an if-else statement, it first checks the expression in the parentheses after the if. If this expression is true, the first command block of statements is executed; otherwise, the command block of statements after the else is executed. In the example, if balance is positive or zero, the first command block is executed to include interest. If balance is negative, the second command block is executed to subtract the penalty. Remark: If the command block of statements contains more than one statement, you have to use braces. Example: BankBalance.html. If you omit the else part of an if-else statement, then you have an if statement. In this case, if the expression in parentheses after the if is true, the command block after the if is executed; otherwise, the command block is skipped and execution of the program continues after the command block. In the example, your bank might not charge a penalty for overdrawn accounts. Then all you need is the following if statement: if (balance >= 0) balance = balance + (INTEREST_RATE * balance)/12;

Conditional Expressions The conditional expression in an if or if-else statement can involve both comparison and logical operators. We already discussed comparison operators, the operators <, <=, >, >=, == used to compare two quantities. Note that == and not the assignment operator = is used to test for equality. logical operators - operators used to compare two boolean quantities. There are three logical operators: && (and) (or)! (not) To understand how these logical operators work, it helps to know their truth tables. P && Q P Q!P Q true false Q true false P P P!P true true false true true true true false false false false false true false false true Example: If a = 2 and b = 3, then a == 2 && b == 4 is false and a == 2 b == 4 is true. Lab 3.5. Explain JavaScript s built-in alert() and prompt() functions. Quiz1.html. while Statements loop statement - a statement that repeatedly executes a statement or block of statements as long as a condition is true. Example: BuckleShoe.html. Note that the while loop includes a counter called count. counter - a variable which is incremented or decremented during each iteration of a loop. A counter is needed to guarantee that the while statement will eventually terminate. Otherwise, an infinite loop occurs and the while loop goes on forever. If an infinite loop occurs, you have to force the Web browser to quit. During each pass through the while statement, we increment the counter by 1 so that the condition in the while statement will eventually be false and the while statement ends. We can decrement as well as increment a counter. Example: BlastOff.html. Lab 3.6. You might want to look at the example in Lesson 4 first. Lesson 5 - Functions and External JavaScript Files function - a collection of statements designed to perform a particular task. parameter or argument - the input variable(s) to a function.

Like variable, the notion of function in computing is the same as function in mathematics. For example, if y = f (x) = 3x 2 +1 and if x = 2, then y = f (2) = 3 2 2 +1=13. x is the parameter or argument for the function. A function may or may not return a value. For example, a function that computes something like an average would return a value. A function that only prints something wouldn t return a value. A function need not have parameters. For example, a function that always prints the same message doesn t need any parameters. A function is defined using the function keyword. The general syntax is: function functionname(parameter1, parameter2,...) { statement1; statement2; (Note the opening and closing {}.)... } Naming functions follows the same rules and conventions as naming variables. A function is executed or called or invoked by including its name and any appropriate parameters in a subsequent JavaScript statement. Functions should be defined in the <HEAD> section, and function calls should be placed in the <BODY> section. Examples: - PrintingFunction.html. - AverageFunction.html. - NoArgsFunction.html. A reminder about JavaScript s built-in alert(), confirm(), and prompt() functions. Variable Scope When you use a variable in a JavaScript program, you need to be aware of its scope. scope - where in a program a variable can be used. global variable - a variable declared outside any function definition; it can be used anywhere in a program. local variable - a variable declared inside a function definition; it can be used only within the function definition. Example: Scope.html. Lab 3.7. Lab 3.8. External JavaScript Files JavaScript is often incorporated directly into an HTML document, as we have been doing. You can also save JavaScript code in an external source file with a.js file extension. The SRC attribute in the <SCRIPT> tag is used to specify the name of the external source file. JavaScript source files cannot include HTML tags. You can use both internal and external JavaScript code. However, each JavaScript section must be included in a separate <SCRIPT>...</SCRIPT> tag pair.

Example: TwoJS.html and External.js. Where to put your JavaScript code: - When do you put JavaScript code directly in an HTML document and when do you use an external file? - If your JavaScript code is fairly short, it s usually easier to include the code directly in the HTML document. - For longer JavaScript code, it s easier to put the code in a.js source file. Advantages of an external file: - Your HTML document will be neater. - The JavaScript code can be shared among multiple HTML documents. - JavaScript code in an external source file is hidden from incompatible browsers. - JavaScript code in an external source file is hidden from other programmers. Code in an HTML document can be viewed.