CITS1231 Web Technologies. JavaScript Math, String, Array, Number, Debugging

Similar documents
Client-Side Web Technologies. JavaScript Part I

Working with JavaScript

Like most objects, String objects need to be created before they can be used. To create a String object, we can write

PES DEGREE COLLEGE BANGALORE SOUTH CAMPUS 1 K.M. before Electronic City, Bangalore WEB PROGRAMMING Solution Set II

Such JavaScript Very Wow

a Why JavaScript? jonkv interactivity on the web CGI JavaScript Java Applets Netscape LiveScript JavaScript 1: Example

CSC Web Programming. Introduction to JavaScript

The first sample. What is JavaScript?

Coding in JavaScript functions

COMS 469: Interactive Media II

Lecture 3: The Basics of JavaScript. Background. Needs for Programming Capability. Origin of JavaScript. Using Client-side JavaScript

Programming language components

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

Introduction to Web Tech and Programming

JAVASCRIPT BASICS. JavaScript String Functions. Here is the basic condition you have to follow. If you start a string with

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

What Is JavaScript? A scripting language based on an object-orientated programming philosophy.

introjs.notebook March 02, 2014

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

710 Index Attributes, 127 action attribute, 263 assigning, bottom attribute, domain name attribute, 481 expiration date attribute, 480 8

Basics of JavaScript. Last Week. Needs for Programming Capability. Browser as Development Platform. Using Client-side JavaScript. Origin of JavaScript

COMP519 Web Programming Lecture 12: JavaScript (Part 3) Handouts

UNIT -II. Language-History and Versions Introduction JavaScript in Perspective-

Introduction to Python

ITEC136 - Lab 2 Population

JavaScript CS 4640 Programming Languages for Web Applications

JavaScript CS 4640 Programming Languages for Web Applications

Exercise 1: Basic HTML and JavaScript

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

Logical Operators. Operators Precedence. break; continue; Loop Control. Logical Operator Examples. Slide Set 7: ObjectTypes, Objects, and Arrays

Code Editor. The Code Editor is made up of the following areas: Toolbar. Editable Area Output Panel Status Bar Outline. Toolbar

CITS1231 Web Technologies. JavaScript

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

15.1 Origins and Uses of Ruby

COMS 469: Interactive Media II

AP Computer Science A

Chapter 4 Basics of JavaScript

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

Javascript Hierarchy Objects Object Properties Methods Event Handlers. onload onunload onblur onfocus

A variable is a name for a location in memory A variable must be declared

LECTURE-2. Functions review HTML Forms. Arrays Exceptions Events. CS3101: Scripting Languages: Javascript Ramana Isukapalli

JavaScript Basics. The Big Picture

c122mar413.notebook March 06, 2013

Full file at

PIC 40A. Lecture 10: JS: Wrapper objects, Input and Output, Control structures, random numbers. Copyright 2011 Jukka Virtanen UCLA 1 04/24/17

Chapter 2 Working with Data Types and Operators

APPENDIX THE TOOLBAR. File Functions

By the end of this section of the practical, the students should be able to:

CSc 337 LECTURE 5: GRID LAYOUT AND JAVASCRIPT

CGS 3066: Spring 2015 JavaScript Reference

USING LIBRARY CLASSES

Manipulating Data in Strings and Arrays

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT

INTRODUCTION TO WEB DEVELOPMENT AND HTML. Lecture 15: JavaScript loops, Objects, Events - Spring 2011

Program Design Phase. Algorithm Design - Mathematical. Algorithm Design - Sequence. Verify Algorithm Y = MX + B

Lab 3 - Pizza. Purpose. Assignment

Darshan Institute of Engineering & Technology for Diploma Studies Unit 2. 2 Working with JavaScript

JavaScript Basics. Mendel Rosenblum. CS142 Lecture Notes - JavaScript Basics

Lab 1 Concert Ticket Calculator

1/16/2013. Program Structure. Language Basics. Selection/Iteration Statements. Useful Java Classes. Text/File Input and Output.

JavaScript: The Basics

The Number object. to set specific number types (like integer, short, In JavaScript all numbers are 64bit floating point

Lab 2 Population. Purpose. Assignment Lab 2 analyzes population growth of a town as well as compare the population growth of two towns.

HTML5 and CSS3 More JavaScript Page 1

JAVASCRIPT BASICS. Type-Conversion in JavaScript. Type conversion or typecasting is one of the very important concept in

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

CSE 373. Data Types and Manipulation; Arrays. slides created by Marty Stepp

JavaScript: Introduction, Types

Strings. Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

Advanced Python. Executive Summary, Session 1

Chapter 1 Introduction to Computers and the Internet

JavaScript Introduction

Pace University. Fundamental Concepts of CS121 1

Chapter 2: Using Data

COMS W3101: SCRIPTING LANGUAGES: JAVASCRIPT (FALL 2017)

We now start exploring some key elements of the Java programming language and ways of performing I/O

Full file at

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

Technical Questions. Q 1) What are the key features in C programming language?

1. Introduction. 2. Scalar Data

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

They grow as needed, and may be made to shrink. Officially, a Perl array is a variable whose value is a list.

Programming with Java

A Balanced Introduction to Computer Science, 3/E David Reed, Creighton University 2011 Pearson Prentice Hall ISBN

5/23/2015. Core Java Syllabus. VikRam ShaRma

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Exercise: Using Numbers

Here n is a variable name. The value of that variable is 176.

Javascript Lesson 3: Controlled Structures ANDREY KUTASH

Outline. Data and Operations. Data Types. Integral Types

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

Index COPYRIGHTED MATERIAL

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting

Language Reference Manual

UNIT-4 JAVASCRIPT. Prequisite HTML/XHTML. Origins

CS313D: ADVANCED PROGRAMMING LANGUAGE

Princess Nourah bint Abdulrahman University. Computer Sciences Department

APPENDIX A: SUMMARY OF IMPORTANT JAVA FEATURES

Chapter 2.4: Common facilities of procedural languages

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

Transcription:

CITS1231 Web Technologies JavaScript Math, String, Array, Number, Debugging

Last Lecture Introduction to JavaScript Variables Operators Conditional Statements Program Loops Popup Boxes Functions 3

This Lecture Functions continued Inbuilt objects Math, String, Array, Number Debugging JavaScript 4

JavaScript References HTML, XHTML and XML (3rd edition -comprehensive), by Patrick Carey, Course Technology. New Perspectives on JavaScript, by Patrick Carey, Frank Canovatchel-in reserve collection. http://www.w3schools.com/js/js_intro.asp 5

Creating a Function to Perform an Action Syntax of a JavaScript function function function_name(parameters){ JavaScript commands } Calling a function function_name(parameter values) 6

Creating a Function to Return a Value For a function to return a value It must include a return statement Syntax of a function that returns a value function function_name(parameters) { JavaScript commands return value; } 7

Lifetime of Variables Local variables When you declare a variable within a function, the variable can only be only accessed within that function. When you exit the function, the variable is destroyed. You can have local variables with the same name in different functions, because each is recognized only by the function in which it is declared. Global variables If you declare a variable outside a function, all the functions on your page can access it. The lifetime of these variables starts when they are declared, and ends when the page is closed. 8

JavaScript Function Example Local variables; Same name ok in different functions. <head> <script type="text/javascript"> varcurmax= 0; function product(a,b) { varresult = a*b; return result; } function sum(a,b) { varresult = a+b; return result; } function updatemax(a) { if (a > curmax) { curmax= a; } </script> </head> } <body> <script type="text/javascript"> varnum1 = 2; varnum2 = 5 ; document.writeln( Product of +num1+ and num2+ = +product(num1,num2)); document.writeln( Sum of +num1+ and num2+ = +sum(num1,num2)); updatemax(num1); updatemax(num2); document.writeln( Current max number i= +curmax); </script> </body> Global variable: Can be accessed from any JavaScript on page. 9

JavaScript Control Flow The previous lecture has briefly touched on the JavaScript Control Flow, namely Conditional statements if, if else switch Iteration or looping for while 10

JavaScript Objects In-built Global Objects Math, String, Array, Number (Rest of this lecture) Date, RegExp, navigator, Event, screen (Next lecture) Document Objects (Subsequent lecture) 11

Window Object Window is the root class, so no need to explicitly specify the class before calling the its functions. There are a set of functions that can create pop-up windows to issue warnings, confirm information and request for user input. See last lecture for examples. alert() confirm() prompt() 12

Array Allows one to use one variable to hold more than one value at a time. Instead of: One can write: var fruit1 = apple ; var fruit2 = orange ; var fruit3 = banana ; varfruits = new Array(); fruits[0] = apple ; fruits[1] = orange ; fruits[2] = banana ; array name // create a new array object // first item // second item // third item This allows one to use for loops to iterate through whole list. Extremely useful if list is very long (eg10 s or 100 s items) array index starts at 0 13

Three Ways to Create Arrays Regular: varfruits = new Array(); // create a new array object fruits[0] = apple ; fruits[1] = orange ; // first item Condensed: var fruits = new Array( apple, orange ); Literal: varfruits = [ apple, orange ]; // second item 14

Accessing and Modifying Array One can access an array element by referring to its name and index number: var fruits = new Array( apple, orange ); document.writeln( Second fruit = + fruits[1]); One can easily modify an array element: var fruits = new Array( apple, orange ); fruits[1] = grape ; document.writeln( Second fruit = + fruits[1]); Output: orange Output: grape 15

Other Array Methods length concat() join() pop() push() reverse() shift() slice() sort() splice() tostring() unshift() valueof() Sets or returns the number of elements in an array Joins two or more arrays, and returns a copy of the joined arrays Joins all elements of an array into a string Removes the last element of an array, and returns that element Adds new elements to the end of an array, and returns the new length Reverses the order of the elements in an array Removes the first element of an array, and returns that element Selects a part of an array, and returns the new array Sorts the elements of an array Adds/Removes elements from an array Converts an array to a string, and returns the result Adds new elements to the beginning of an array, and returns the new length Returns the primitive value of an array 16

Array concat() and length 17 <html><body> <pre> <script type="text/javascript"> var fruits = new Array( "apple", "orange"); var veges = new Array( "carrot", "lettuce", "spinach"); var shopping = fruits.concat(veges); document.writeln("shopping list of "+shopping.length+" items:"); document.writeln(shopping); document.writeln(""); document.writeln("using for loop to list items:"); document.writeln("<ul>"); for(vari=0; i<shopping.length; i++) { document.writeln("<li>"+shopping[i]+"</li>"); } document.writeln("</ul>"); </script> </pre> </body></html> concat() combines arrays length gives array length

Math Object JavaScript provides built in mathematical methods through its Math objects. The math methods are applied in the following manner, SinOfAngle = Math.sin(Angle); Some important methods are Math Math.abs(value) (absolute value) Math.sin(value) (sine of angle value) Math.round(value) (round value to nearest integer) Math.ceil(value) (round up to next integer) Math.floor(value) (round down to next integer). 18

Math Methods 19

Math Constants 20

Global Numeric Functions isfinite() -determines if a value is a finite, legal number isfinite(1.23); isfinite( hello ); isnan() -determines whether a value is an illegal number isnan(1.23); isnan( hello ); parsefloat() - parses string and returns floating number parsefloat( 1.23 ); parseint() Parses a string and returns an integer parseint( 1234 ); Returns: true Returns: false Returns: false Returns: true Returns: 1.23 Returns: 1234 21

Number Object Functions varnum = 123.456; toexponential(x) -converts number to exponential form. num is optional and specifies # of digits after decimal num.toexponential(); num.toexponential(1); tofixed(x) - formats number with x digits after decimal num.tofixed(2); toprecision(x) -formats a number to x length num.toprecision(4); Returns: 1.23456e+2 Returns: 1.2e+2 Returns: 123.45 Returns: 123.4 22

Strings Object String objects are used to manipulate text. Example of how to create a string: var first_name = John ; length property: document.writeln(first_name.length); Method touppercase(): document.writeln(first_name.touppercase()); Method tolowercase(): document.writeln(first_name.tolowercase()); Output: 4 Output: JOHN Output: john 23

Strings Object Continued var first_name = John ; charat(index) returns character at the index: document.writeln(first_name.charat(2); concat(str) returns copy of given string joined with str: document.writeln(first_name.concat( ny )); replace(str1, str2) replaces substring str1 with str2: document.write(first_name.replace("hn","e")); substr(start,len) extracts substring of lencharacters long starting at index start document.write(first_name.substr(1,2)); Output: h Output: Johnny Output: Joe Output: oh 24

Other String Methods charcodeat() Returns the Unicode of the character at the specified index fromcharcode() Converts Unicode values to characters indexof() lastindexof() match() search() slice() split() substring() valueof() Returns position of first found occurrence of specified value in string Returns position of last found occurrence of specified value in string Searches for match between regular expression and string, and returns the matches Searches for a match between a regular expression and a string, and returns the position of the match Extracts a part of a string and returns a new string Splits a string into an array of substrings Extracts the characters from a string, between two specified indices Returns the primitive value of a String object 25

String HTML Wrapper Methods HTML wrapper methods return the string wrapped inside an HTML tag. Examples: varstr= blah ; anchor(anchorname) creates an anchor: str.anchor( theanchor ); link(url) creates link: str.link( http://thelink.com ); bold() creates a string embedded in <b> tag: str.bold(); Output: <a name= theanchor >blah</a> Output: <a href= http://thelink.com >blah</a> Output: <b>blah</b> 26

Other HTML Wrapper Methods big() blink() fixed() fontcolor() fontsize() italics() small() strike() sub() sup() Displays a string using a big font Displays a blinking string Displays a string using a fixed-pitch font Displays a string using a specified color Displays a string using a specified size Displays a string in italic Displays a string using a small font Displays a string with a strikethrough Displays a string as subscript text Displays a string as superscript text 27

Debugging Your JavaScript Programs Load-time error Occurs when script is first loaded by JavaScript interpreter Run-time error Occurs after script has been successfully loaded and is being executed Logical errors Free from syntax and structural mistakes, but result in incorrect results 28

Illustrating a Logical Error 29

Common Mistakes Common errors Misspelling a variable name Mismatched parentheses or braces Mismatched quotes Missing quotes Debugging Process of searching code to locate a source of trouble 30

Debugging Tools and Techniques Writing modular code Breaking up a program s different tasks into smaller, more manageable chunks Alert dialog box Dialog box generated by JavaScript that displays a text message with an OK button Microsoft Script Debugger Can help to create and debug JavaScript programs 31

Microsoft Debugger Window 32

Tips for Writing Good JavaScript Code Apply layout techniques to make code more readable Use descriptive variable names Be consistent in how you apply uppercase and lowercase letters to your variable names Add comments to your code Create customized functions Break up long and complicated functions into smaller functions Use the debugging tools available In case of a logical error, use alert boxes 33