CS1520 Recitation Week 2

Similar documents
4.1 Overview of JavaScript

JavaScript I VP R 1. Copyright 2006 Haim Levkowitz. Outline

ID1354 Internet Applications

Javascript Methods. concat Method (Array) concat Method (String) charat Method (String)

JavaScript: More Syntax and Using Events

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

Client-Side Web Technologies. JavaScript Part I

UNIT-4 JAVASCRIPT. Prequisite HTML/XHTML. Origins

JavaScript CS 4640 Programming Languages for Web Applications

CSC Web Programming. Introduction to JavaScript

JavaScript CS 4640 Programming Languages for Web Applications

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

Chapter 4 Basics of JavaScript

COMS 469: Interactive Media II

Chapter 3 Data Types and Variables

Princess Nourah bint Abdulrahman University. Computer Sciences Department

JavaScript: More Syntax

PHP. Interactive Web Systems

More on new. Today s Goals. CSCI 2910 Client/Server-Side Programming. Creating/Defining Objects. Creating/Defining Objects (continued)

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

Client vs Server Scripting

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

JavaScript: The Basics

HTML5 and CSS3 More JavaScript Page 1

Web Site Design and Development JavaScript

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 Lecture 1

JavaScript by Vetri. Creating a Programmable Web Page

Welcome to CS50 section! This is Week 10 :(

CGS 3066: Spring 2015 JavaScript Reference

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

Chapter 1 Introduction to Computers and the Internet

Javascript. UNIVERSITY OF MASSACHUSETTS AMHERST CMPSCI 120 Fall 2010

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

JavaScript Introduction

SEEM4570 System Design and Implementation Lecture 03 JavaScript

CS312: Programming Languages. Lecture 21: JavaScript

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

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

Why Discuss JavaScript? CS312: Programming Languages. Lecture 21: JavaScript. JavaScript Target. What s a Scripting Language?

IAT 355 : Lab 01. Web Basics

JAVASCRIPT. JavaScript is the programming language of HTML and the Web. JavaScript Java. JavaScript is interpreted by the browser.

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

JQuery and Javascript

JavaScript: Sort of a Big Deal,

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

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

COMS 469: Interactive Media II

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

Python Intro GIS Week 1. Jake K. Carr

JavaScript: Introduction, Types

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

Introduction to JavaScript p. 1 JavaScript Myths p. 2 Versions of JavaScript p. 2 Client-Side JavaScript p. 3 JavaScript in Other Contexts p.

Values and Variables 1 / 30

COMS W3101: SCRIPTING LANGUAGES: JAVASCRIPT (FALL 2018)

Manju Muralidharan Priya. CS4PM Web Aesthetics and Development WEEK 11

Chapter 17. Fundamental Concepts Expressed in JavaScript

Tutorial 10: Programming with JavaScript

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

Chapter 2 Working with Data Types and Operators

XQ: An XML Query Language Language Reference Manual

PHP Hypertext Preprocessor

COMP6700/2140 Data and Types

PHP 5 Introduction. What You Should Already Know. What is PHP? What is a PHP File? What Can PHP Do? Why PHP?

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Elementary Programming

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

Chapter 12. JavaScript 1: Basic Scripting Table of Contents

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

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

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

FORMULAS QUICK REFERENCE

Outcomes Week 2 Overview Describe the inputs, activities, and outputs of each step in the software development life cycle. Describe arithmetic, relati

Session 3: JavaScript - Structured Programming

5. Using the precendence rules for arithmetic operators, determine which statement is true.

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

DC71 INTERNET APPLICATIONS JUNE 2013

<script type="text/javascript"> script commands </script>

Full file at Tutorial 2: Working with Operators and Expressions

(CONDITIONALS_BOUNDARY)

EECS1012. Net-centric Introduction to Computing. Lecture Introduction to Javascript

CHIL CSS HTML Integrated Language

Full file at

ArcGIS API for JavaScript: Using Arcade with your Apps. Kristian Ekenes & David Bayer

SECTION II: LANGUAGE BASICS

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

CS 314 Principles of Programming Languages

CS2141 Software Development using C/C++ C++ Basics

JAVASCRIPT. sarojpandey.com.np/iroz. JavaScript

Language Fundamentals Summary

Zheng-Liang Lu Java Programming 45 / 79

Java+- Language Reference Manual

Such JavaScript Very Wow

URLs and web servers. Server side basics. URLs and web servers (cont.) URLs and web servers (cont.) Usually when you type a URL in your browser:

CS 130(0) JavaScript Lab

Midterm Exam. 5. What is the character - (minus) used for in JavaScript? Give as many answers as you can.

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

Transcription:

CS1520 Recitation Week 2 Javascript http://cs.pitt.edu/~jlee/teaching/cs1520 Jeongmin Lee, (jlee@cs.pitt.edu)

Today - Review of Syntax - Embed code - Syntax - Declare variable - Numeric, String, Datetime Objects - Control statements - Array - Function - Object - == vs. === Many examples are based on w3schools.com and tutorialspoint.com

Review of syntax

Embed code of javascript 3 Ways to include <script>//directly write code here</script> <script src= path/to/file.js ></script> <script src= http://www.scripts.com/file.js ></scr ipt> Scripts should go as close to the closing <body> tag as possible in your markup

Syntax Identifier should begin with a letter or underscore (numbers cannot be the first character) Case sensitive Comments: // and /*.. */ Semicolons are optional to use but in this class required.

Declare variable Variables can be implicitly or explicitly declared. var mynum = 0; var mystring = Hello world ; var myarray = []; // equiv. to var myarray = new Array(); Var myobj = {}; // var myobj = new Object();

Numeric operators Variables can be implicitly or explicitly declared. Numeric operators - ++, --, +, -, *, /, % All operations are in double precision The Math Object provides floor, round, max, min, trig functions, etc. e.g., Math.cos(x) The Number Object Some useful properties: MAX_VALUE, MIN_VALUE, NaN, POSITIVE_INFINITY, NEGATIVE_INFINITY, PI e.g., Number.MAX_VALUE

String operators Concatenation e.g, var str1 = hello + + world ; length e.g., var len = str1.length; (a property) charat(position) e.g., str.charat(3) indexof(string) e.g., str.indexof('b') substring(from, to) e.g., str.substring(1, 3) tolowercase() e.g., str.tolowercase()

Date object and operators The Date Object Create one with the Date constructor (no params) Local time methods of Date: tolocalestring returns a string of the date getdate returns the day of the month getmonth returns the month of the year (0 11) getday returns the day of the week (0 6) getfullyear returns the year gettime returns the number of milliseconds since January 1, 1970 gethours returns the hour (0 23) getminutes returns the minutes (0 59)

Control

Control statements Control expressions three kinds Primitive values (True or False) If it is a string, it is true unless it is empty or "0" If it is a number, it is true unless it is zero Relational Expressions The usual six: ==,!=, <, >, <=, >= Operands are coerced if necessary If one is a string and one is a number, it attempts to convert the string to a number If one is Boolean and the other is not, the Boolean operand is coerced to a number (1 or 0) Compound Expressions The usual operators: &&,, and!

Control statements Switch switch (expression) { } case value_1: // value_1 statements case value_2: // value_2 statements [default: // default statements] The statements can be either statement sequences or compound statements The control expression can be a number, a string, or a Boolean Different cases can have values of different types

Control statements Loop statements while (control_expression) statement or compound for (init; control; increment) statement or compound init can have declarations, but the scope of such variables is the whole script do {statement or compound} while (control_expression)

== vs. ===

== vs. === JavaScript has both strict (===,!==) and type-converting (==,!=) equality comparison. For strict equality the objects being compared must have the same type. Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions. Two numbers are strictly equal when they are numerically equal (have the same number value). NaN is not equal to anything, including NaN. Positive and negative zeros are equal to one another. Source: MDC (https://developer.mozilla.org/en/core_javascript_1.5_reference/operat ors/comparison_operators)

== vs. === Two Boolean operands are strictly equal if both are true or both are false. Two objects are strictly equal if they refer to the same Object. Null and Undefined types are == (but not ===). [I.e. (Null==Undefined) is true but (Null===Undefined) is false] Source: MDC (https://developer.mozilla.org/en/core_javascript_1.5_reference/operat ors/comparison_operators)

== vs. === console.log(3 == "3"); // true; type conversion happened console.log(3 === "3"); // false. Source: https://appendto.com/2016/02/vs-javascript-abstract-vs-strict-equality/

== vs. === console.log(true == '1'); // true console.log(true === '1'); // false Source: https://appendto.com/2016/02/vs-javascript-abstract-vs-strict-equality/

== vs. === console.log(undefined == null); // true console.log(undefined === null); // false. Undefined and null are distinct types and are not interchangeable. Source: https://appendto.com/2016/02/vs-javascript-abstract-vs-strict-equality/

== vs. === console.log(true == 'true'); // false. A string will not be converted to a boolean and vice versa. console.log(true === 'true'); // false Source: https://appendto.com/2016/02/vs-javascript-abstract-vs-strict-equality/

== vs. === console.log("this is a string." == new String("This is a string.")); // true console.log("this is a string." === new String("This is a string.")); // false Strings literals are different from string objects console.log(typeof "This is a string."); // string console.log(typeof new String("This is a string.")); //object Source: https://appendto.com/2016/02/vs-javascript-abstract-vs-strict-equality/

== vs. === var a = []; var b = []; var c = a; console.log(a == b); // false console.log(a === b); // false => When comparing reference types both abstract and strict comparisons will return false unless both operands refer to the exact same object console.log(a == c); // true console.log(a === c); // true Source: https://appendto.com/2016/02/vs-javascript-abstract-vs-strict-equality/

Array

Arrays Array is an object with some special functionality Its values can be primitive values or references to other objects Length is dynamic Create in (1) new or (2) by assigning an array literal [] var mylist = new Array(24, "bread", true); var mylist2 = [24, "bread", true]; var mylist3 = new Array(24);

Functions

Function Return value is the parameter of return If there is no return, or if the end of the function is reached, undefined is returned, If return has no parameter, undefined is returned Functions are objects, so variables that reference them can be treated as other object references function myfunction(p1, p2) { return p1 * p2; // The function returns the product } var x = myfunction(4, 3); // Function is called, return value will end up in x

Write / Modify something in HTML with JS.

Write/Modify something in HTML with JS. You have a HTML page with some elements in it. You want to write / modify HTML elements with JS. Then you can do this 1) Get specific HTML element with its id document.getelementbyid( [id] ) This element with this [id] will be changed 2) Replaces content of the elemnt with innerhtml method document.getelementbyid( [id] ).innerhtml = newcontent 3) If the element you change is hyperlink, you can use href method document.getelementbyid( [id] ).href = http://pitt.edu

Write/Modify something in HTML with JS. Example code <!DOCTYPE html> <html> <body> <a id="myanchor" href="http://www.pitt.edu">u Pitt website</a> <button onclick="myfunction()">change link</button> <script> function myfunction() { document.getelementbyid("myanchor").innerhtml = "Pitt CS"; document.getelementbyid("myanchor").href = "http://cs.pitt.edu"; } </script> </body> </html>

Object

Object Creation and Modification Objects can be created with new or with just {} The most basic object is one that uses the Object constructor, as in var myobject = new Object(); Properties can be added to an object, any time var mycomic = new Object(); var mycomic = {}; literal mycomic.publisher = "Image"; mycomic.title = "Seven To Eternity"; Objects can be nested, so a property could be itself another object, created with new {}

Example: a car object Let s think about we have a car with these properties and methods. Property Name = Fiat Model = 500 Weight = 1000 lbs Color = white What it can do Start Stop Accelerate Brake

Example: a car object And modeling these into JS properties and methods would be something like this... (We will see how to define soon) Property Name = Fiat Model = 500 Weight = 1000 lbs Color = white Property car.name = Fiat car.model = 500 car.weight = 1000 car.color = white What it can do Start Stop Accelerate Brake Methods car.start() car.stop() car.accelerate() car.brake()

Example: a car object First create a HTML page with paragraph element with id of demo. At this stage, nothing would be shown on webpage but h1 title. <!DOCTYPE html> <html> <body> <h1> Car object demo page </h1> <p id="demo"></p> </body> </html>

Example: a car object Let s add javascript that create variable car. Add script block first, and then create a variable within there. <!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var car = "Fiat"; </script> </body> </html>

Example: a car object Now, we will make the p element to have name of car object ( Fiat ). <!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var car = "Fiat"; document.getelementbyid("demo").innerhtml = car; </script> </body> </html>

Example: a car object Another way to make an object: with its properties. And let s see its type on html page. <!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var car = {type:"fiat", model:"500", color:"white"}; document.getelementbyid("demo").innerhtml = car.type; </script> </body> </html>

Example: a car object Now, let s work on methods! First, let s have status and speed property. <!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var car = {type:"fiat" model:"500", color:"white", status: stop, speed: 0}; document.getelementbyid("demo").innerhtml = car.status; </script> </body> </html>

Example: a car object Let s create a method of start. It changes status. <!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var car = {type:"fiat", model:"500", color:"white", status: stop, speed: 0, start(){this.status = running }}; document.getelementbyid("demo").innerhtml = car.status; car.start(); document.getelementbyid("demo").innerhtml = car.status; </script> </body> </html>

Questions?

Exercise!

Exercise: add your own methods First, create your own html file Just copy, paste and save the code it on your computer Add new methods and check to see it works. Stop: change status variable to stop Accelerate: increment speed by +5 Brake: decrement speed by -5 <!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var car = {type:"fiat", model:"500", color:"white", status: stop, speed: 0, start(){this.status = running }}; car.start(); document.getelementbyid("demo").innerhtml = car.status; </script> </body> </html>