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

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

Client-Side Web Technologies. JavaScript Part I

JavaScript CS 4640 Programming Languages for Web Applications

JavaScript CS 4640 Programming Languages for Web Applications

Such JavaScript Very Wow

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

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

CSC Web Programming. Introduction to JavaScript

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

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

Web Application Development

CS312: Programming Languages. Lecture 21: JavaScript

CGS 3066: Spring 2015 JavaScript Reference

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

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

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

JavaScript. Training Offer for JavaScript Introduction JavaScript. JavaScript Objects

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

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

JavaScript: The Basics

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

Chapter 3 Data Types and Variables

CSCE 120: Learning To Code

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

JavaScript Lecture 1

JavaScript: Introduction, Types

INF5750. Introduction to JavaScript and Node.js

JavaScript for PHP Developers

This course is designed for web developers that want to learn HTML5, CSS3, JavaScript and jquery.

The JavaScript Language

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

CSCI-GA Scripting Languages

COMP284 Scripting Languages Lecture 14: JavaScript (Part 1) Handouts

Part 1: jquery & History of DOM Scripting

Index COPYRIGHTED MATERIAL

JScript Reference. Contents

Symbols. accessor properties, attributes, creating, adding properties, 8 anonymous functions, 20, 80

JavaScript Introduction

JavaScript Basics. The Big Picture

JavaScript: the language of browser interactions. Claudia Hauff TI1506: Web and Database Technology

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

Variables and Typing

Principles of Programming Languages

Chapter 4 Basics of JavaScript

Node.js Training JavaScript. Richard richardrodger.com

Introduction to Programming Using Java (98-388)

Lecture 8 (7.5?): Javascript

The course is supplemented by numerous hands-on labs that help attendees reinforce their theoretical knowledge of the learned material.

FALL 2017 CS 498RK JAVASCRIPT. Fashionable and Functional!

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

The JavaScript Language

Ruby: Introduction, Basics

JavaScript: Sort of a Big Deal,

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

SEEM4570 System Design and Implementation Lecture 03 JavaScript

Ruby: Introduction, Basics

JavaScript. The Bad Parts. Patrick Behr

COMS 469: Interactive Media II

Pace University. Fundamental Concepts of CS121 1

Web Site Design and Development JavaScript

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

JavaScript I Language Basics

TypeScript. Types. CS144: Web Applications

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

Princess Nourah bint Abdulrahman University. Computer Sciences Department

Working with JavaScript

5. Strict mode use strict ; 6. Statement without semicolon, with semicolon 7. Keywords 8. Variables var keyword and global scope variable 9.

Documents and computation. Introduction to JavaScript. JavaScript vs. Java Applet. Myths. JavaScript. Standard

CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square)

1. Introduction. 2. Scalar Data

CSc 337 LECTURE 5: GRID LAYOUT AND JAVASCRIPT

Program Fundamentals

Ruby: Introduction, Basics

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

MATVEC: MATRIX-VECTOR COMPUTATION LANGUAGE REFERENCE MANUAL. John C. Murphy jcm2105 Programming Languages and Translators Professor Stephen Edwards

COMP519 Web Programming Lecture 14: JavaScript (Part 5) Handouts

B l o c k B i n d i n g s

(2½ hours) Total Marks: 75

Chapter 2 Working with Data Types and Operators

Java Overview An introduction to the Java Programming Language

Node.js. Node.js Overview. CS144: Web Applications

Functional Programming. Pure Functional Programming

XML JavaScript Object Notation JSON Cookies Miscellaneous What Javascript can t do. OOP Concepts of JS

PERL Scripting - Course Contents

Decaf Language Reference Manual

JavaScript Programming

Princeton University COS 333: Advanced Programming Techniques A Subset of JavaScript

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Language Features. 1. The primitive types int, double, and boolean are part of the AP

FRAC: Language Reference Manual

CSC Web Technologies, Spring Web Data Exchange Formats

PHP. Interactive Web Systems

Scheme as implemented by Racket

UNIT-4 JAVASCRIPT. Prequisite HTML/XHTML. Origins

JavaScript: The Definitive Guide

Javascript. Many examples from Kyle Simpson: Scope and Closures

CS112 Lecture: Primitive Types, Operators, Strings

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming

JavaScript or: HOW I LEARNED TO STOP WORRYING AND LOVE A CLASSLESS*

Introduction to Web Tech and Programming

Transcription:

JavaScript Started as a simple script in a Web page that is interpreted and run by the browser Supported by most modern browsers Allows dynamic update of a web page More generally, allows running an arbitrary code inside a browser! * Both a blessing and a curse Now, JavaScript can run anywhere, phone, tablet, desktop, server, not just in a browser History 1995 Netscape Navigator added a support for a simple scripting language named LiveScript Renamed it to JavaScript in 1996 JavaScript has nothing to do with Java! 1997 ECMA International standardized the language submitted by Netscape ECMAScript: Official name of the standard Javascript: What people call it 1998 ECMAScript 2, 1999 ECMAScript 3 ECMAScript 4 abandoned due to disagreement 2009 ECMAScript 5 2015 ECMAScript 6 (= ECMAScript 2015) Yearly release of new standard from ECMAScript 2015 We learn syntax based on ECMAScript 2015 Most books and online tutorials are based on ECMAScript 5 A lot of ECMAScript 5 legacy code exist today Our syntax may be different from these But the newer standard removes much ugliness of old JavaScript Adding JavaScript to a page < script >... javascript code... Junghoo "John" Cho (cho@cs.ucla.edu) 1

</ script > < script src =" script. js " ></ script > <script> may appear anywhere on a page Basic keywords and syntax Syntax is very close to java/c if (cond){ stmt; else if (cond){ stmt; switch (a){ case: 1;...; default:...; while (i < 0){ stmt; for (i=0; i < 10; i++){ stmt; for (e of array){ stmt; //loop over array-like elements try { throw 1; catch (e if e === ".."){ stmt finally { stmt JavaScript is case sensitive But HTML is NOT. This discrepancy sometimes causes confusion. Variables let name=value; // variable type is dynamic A variable can be used without an explicit let declaration * becomes a global variable * But this is strongly discouraged Constant: const n = 42; // n cannot be reassigned or redeclared Before ECMAScript 2015, var was used instead of let with some differences * function scope vs block scope * hoisting vs no hoisting * Use of let produces much cleaner code Function declaration statement function func_name ( parameter1, parameter2,...) {... function body... return value ; Junghoo "John" Cho (cho@cs.ucla.edu) 2

JavaScript identifiers (like variable or function name) may have letters, numbers, _, and $ Comparison operators ==/!= true if operands have the same value (after type conversion) ===/!== true only if operands have the same value and type (no automatic type conversion) * 3 == "3" vs 3 === "3" When operands are objects, ==/=== returns true only if both operands reference the same object (more on this later) Logical AND and OR operators: && and Primitive Types JavaScript is a dynamically-typed language Variables do not have a static type. Types may change over time. let a = 10; // a is number type a = " good "; // a is string type Types are either primitive type or object type Primitive data types number, string, boolean (and null and undefined) number type All numbers are represented as a floating point number (double in C). No separate integer type Bitwise operators (&,, ^, >>, <<) represent a number as a 32-bit integer after truncating subdecimal digits NaN and Infinity are valid numbers boolean type true or false other falsy values: 0,, null, undefined, NaN Junghoo "John" Cho (cho@cs.ucla.edu) 3

string type Single or double quotes: 'John' or "John" length property returns the length of the string Many useful string functions exist: charat(), substring(), indexof(),... let a = " abcdef "; b = a. substring (1, 4) ; // b = " bcd " numbers and string are automatically type converted to each other 3 * 4 = 12 1+ 2 = 12 For explicit type conversion, use Number(), String(), Boolean(), parsefloat(), parseint(),... Regular expression Describes a pattern to search for in a string let r = /a?b*c /; Can be used in the following functions String: search(), match(), replace(), split() RegExp: exec(), test() Examples / ABC /. test ( str ); // true if str has substr ABC / ABC /i. test ( str ); // i ignores case /[ Aa ]B[C -E ]/. test ( str ); // [ Aa ]: A or a, [C -E ]: C thru E ' 123 abbbc '. search (/ ab *c /) ; // 3 ( position of 'a ') '12 e34 '. search (/[^\ d ]/) ; // 2 [^ x ]: except x, \d: digit To be precise, RegExp is a special object type Junghoo "John" Cho (cho@cs.ucla.edu) 4

undefined and null type undefined: the type of the value undefined A variable has the value undefined before initialization null: the type of the value null null is mainly used to represent the absence of an object For legacy reasons, most systems return object as the type of null value undefined and null are often interchangeably used, but they are different in principle undefined == null ; // true undefined === null ; // false typeof operator returns the current type of the variable typeof null is object for legacy issues Object Type All non-primitive types in JavaScript are object type Object: data with a set of properties let o = { x :1, y:" good " ; let c = o.x + o["y" ]; let p = new Object () ; p.x = 10; p["y"] = " good "; delete p.x; // delete property x from p let q = { x :1, y :2, z :{ x :3, y :4 ; // objects can be nested Note: o["x"] is identical to o.x. Objects are essentially an associative array. Properties can be added, removed, and listed let o = { x :10, y :20 ; o.z = 30; delete o.x; Junghoo "John" Cho (cho@cs.ucla.edu) 5

Object. keys (o); Object assignment is by reference, not by value Object comparison is also by reference not by value Array Array is a special object with integer-indexed items Created with new Array(), or [ 1, 2, 3 ] let a = new Array () ; a [0] = 3; a [2] = " string "; let b = new Array (1, 2, 3) ; let c = [1, 2, 3]; let sizec = c. length ; // sizec is 3 length property returns the size of the array Can be used to resize array as well (by setting its value) Array can be sparse and its elements types may be heterogeneous let a = [1, " good ",, [2, 3] ]; Size of an array automatically increased whenever needed a = [1, 2]; a [3] = 4; // a. length == 4 here Array manipulation functions Mutators: changes input array directly reverse, sort, push, pop, shift, unshift * Accessors: input array stays in tact. new output array is created * concat, join (into a string), slice Junghoo "John" Cho (cho@cs.ucla.edu) 6

let a = [1, 2, 3, 4]; b = a. slice (1, 3) ; // b = [2, 3] Function In Javascript, functions are objects! Functions can be assigned to a variable Functions can be passed as a parameter Functions can have properties let square = function (x) { return x ** x; ; // anonymous function // function definition expression square (10) ; // => 100 function myfunc (x, func ) { return func (x); myfunc (10, square ); // => 100 myfunc (10, function (x) { return x * 2; ) ; // => 20 myfunc. a = 20; Arrow function expression (ECMAScript 2015) Shorthand notation for function definition expression * * * (param1,..., paramn)=> { statements (param1,..., paramn)=> expression singleparam => expression () => { statements * Very convenient for Node.js programming Junghoo "John" Cho (cho@cs.ucla.edu) 7

Object-Oriented Programming (OOP) Objects can have methods let o = new Object () ; o.x = 1; o. doublex = function () { this.x *= 2; this inside an object s method points to the object Equivalently, the invocation context of an object s method is the object itself Class ECMAScript 2015 added support for classes and inheritance class Rectangle extends Shape { // Constructor constructor ( color, height, width ) { super ( color ); // super points to the parent class this. height = height ; this. width = width ; // Method calcarea () { return this. height * this. width ; // Class - wide static properties and methods static name = " Rectangle Class "; // Getter get area () { return this. calcarea () ; // Setter set x(v) { this. coordx = v; ; let r = new Rectangle (2, 3) ; Junghoo "John" Cho (cho@cs.ucla.edu) 8

r. area ; // => 6 r.x = 10; // r. coordx = 10 Rectangle. name // => " Rectangle class " Scope Global vs local scope A variable declared with let inside a block is valid only within the block: block-scope local variable A variable declared outside of any block has global scope. A variable that is assigned to a value without an explicit let declaration has global scope. let a = " global_a "; // global b = " global_b "; // global function f () { c = " global_c "; // global let d = " local_d "; // local Technically speaking: Global variables are properties of the global object (in case of browser, window) Local variables within a function are properties of the call object (= invocation context), which is created when the function is invoked this: * if outside of any function, this = global object * if inside a function, this = call object of the function * if inside an object method, this = the object Functions can be nested function f () { let a = 1; // a is local to f () Junghoo "John" Cho (cho@cs.ucla.edu) 9

function g () { let b = 2; // b is local to g () a = 3; // b == undefined here // a == 3 here // a == undefined here JavaScript is based on lexical scope JavaScript Object Notation (JSON) The standard syntax to represent literal objects in JavaScript (with some restrictions) e.g., [{ "x": 3, "y": "Good", { "x": 4, "y": "Bad"] Q: What does the this notation mean in JavaScript? Compared to JavaScript, the main differences are * Object property names require double quotes * Strings need double quotes, not single quotes_ * JSON values cannot be functions or undefined JSON-related functions: JSON.stringfy(): JavaScript object -> JSON string JSON.parse(): JSON string -> JavaScript object Example let x = '[{ "x ": 3, "y ": " Good ", { "x ": 4, "y ": " Bad " ] '; let o = JSON. parse (x); let n = o [0]. x + o [1]. x; // n = 7 JSON has become one of the two most popular data-exchange format on the Web Based on JavaScript Easy to understand Junghoo "John" Cho (cho@cs.ucla.edu) 10

Modules ECMAScript 2015 Module ECMAScript 2015 added support for modules One module <-> One JavaScript file Everything in a module stays local unless declared export export entities can be imported and used by another JavaScript code Multiple named export example // ------ lib. js ------ export function square (x) { return x * x; export function dist (x, y) { return Math. sqrt ( square (x) + square (y)); // ------ main. js ------ import { square, dist from './ lib '; square (11) ; // => 121 dist (4, 3) ; // => 5 // ----- main2. js ------ import * as lib from './ lib '; lib. square (11) ; // => 121 lib. dist (4, 3) ; // => 5 Single default export // ------ myfunc. js ------ export default function () {... // ------ main1. js ------ import myfunc from ' myfunc '; myfunc () ; Junghoo "John" Cho (cho@cs.ucla.edu) 11

Node.js Module Unfortunately, Node.js s support of modules is non-standard (based on CommonJS module) Node.js started supporting modules way before ECMAScript 2015 Due to difference in their behavior, it is difficult to support ECMA standard in a backward-compatible manner Example // ------ lib. js ------ exports. square = function (x) { return x * x; exports. dist = function (x, y) { return Math. sqrt ( square (x) + square (y)); // ------ main. js ------ let lib = require ( './ lib '); lib. square (11) ; // => 121 lib. dist (4, 3) ; // => 5 References Javascript: The Definitive Guide by David Flanagan Strongly recommended if you plan to code in JavaScript extensively ECMAScript standard: ECMA 262 https://www.ecma-international.org/ecma- 262/ The ultimate reference on what is really correct But very boring to read and learn from Browser support is a few generations behind Summary of new features in ECMAScript 2015: http://es6-features.org/ JSON standard: ECMA 404 http://www.json.org/ Junghoo "John" Cho (cho@cs.ucla.edu) 12