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

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

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

INF5750. Introduction to JavaScript and Node.js

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

JavaScript CS 4640 Programming Languages for Web Applications

Chapter 3 Data Types and Variables

JavaScript Programming

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

FALL 2017 CS 498RK JAVASCRIPT. Fashionable and Functional!

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

JavaScript Introduction

CGS 3066: Spring 2015 JavaScript Reference

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

JavaScript: The Basics

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

JavaScript. What s wrong with JavaScript?

JavaScript Lecture 1

Node.js Training JavaScript. Richard richardrodger.com

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

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

CSc 337 LECTURE 5: GRID LAYOUT AND JAVASCRIPT

Parsing Scheme (+ (* 2 3) 1) * 1

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

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

The JavaScript Language

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

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

Web Application Development

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

Chapter 4 Basics of JavaScript

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

JavaScript Basics. The Big Picture

PERL Scripting - Course Contents

Ruby: Introduction, Basics

JavaScript. The Bad Parts. Patrick Behr

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

CSC Web Programming. Introduction to JavaScript

JavaScript. Training Offer for JavaScript Introduction JavaScript. JavaScript Objects

Ruby: Introduction, Basics

JavaScript: Sort of a Big Deal,

SEEM4570 System Design and Implementation Lecture 03 JavaScript

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

CS312: Programming Languages. Lecture 21: JavaScript

The results for a few specific cases below are indicated. allequal ([1,1,1,1]) should return true allequal ([1,1,2,1]) should return false

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Principles of Programming Languages

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

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

Test 1 Summer 2014 Multiple Choice. Write your answer to the LEFT of each problem. 5 points each 1. Preprocessor macros are associated with: A. C B.

Such JavaScript Very Wow

JavaScript: Introduction, Types

COMP284 Scripting Languages Lecture 15: JavaScript (Part 2) Handouts

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

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

1. Introduction. 2. Scalar Data

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

Busy.NET Developer's Guide to ECMAScript

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

JScript Reference. Contents

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

COMS 469: Interactive Media II

Functional JavaScript. Douglas Crockford Yahoo! Inc.

Princess Nourah bint Abdulrahman University. Computer Sciences Department

Algorithms & Datastructures Laboratory Exercise Sheet 1

JavaScript: More Syntax

JAVASCRIPT FOR THE C# DEVELOPER

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

JavaScript Lecture 2

JavaScript for C# Programmers Kevin

ID1354 Internet Applications

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

JavaScript: The Good Parts

Ans: Store s as an expandable array of chars. (Double its size whenever we run out of space.) Cast the final array to a String.

Ruby: Introduction, Basics

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

Index COPYRIGHTED MATERIAL

JavaScript or: How I Learned to Stop Worrying and Love a Classless Loosely Typed Language

Introduction to Web Tech and Programming

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

JavaScript: More Syntax and Using Events

USING LIBRARY CLASSES

JavaScript: The Good Parts. Douglas Crockford Yahoo! Inc.

Scripting for Multimedia LECTURE 3: INTRODUCING JAVASCRIPT

Lecture 9: Parameter Passing, Generics and Polymorphism, Exceptions

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

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

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

Scripting Languages Perl Basics. Course: Hebrew University

Pascal: operations on basic data structures (selection) (I) 2.3 Accessing and manipulating data

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Principles of Programming Languages

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

JavaScript: Coercion, Functions, Arrays

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

More Perl. CS174 Chris Pollett Oct 25, 2006.

Quiz 1. In class on Tuesday (April 14) Review learning goals (from lecture) Review lectures 1 4, PSA 1 You should be able to:

JavaScript for PHP Developers

Transcription:

JavaScript Basics Mendel Rosenblum 1

What is JavaScript? From Wikipedia:... high-level, dynamic, untyped, and interpreted programming language... is prototype-based with first-class functions,... supporting object-oriented, imperative, and functional programming... has an API for working with text, arrays, dates and regular expressions Not particularly similar to Java: More like C crossed with Self/Scheme C-like statements with everything objects, closures, garbage collection, etc. Also known as ECMAScript 2

Some thoughts about JavaScript Example of a scripting language Interpreted, less declaring of things, just use them Seems like it was designed in a rush Some Good Parts, some not so good Got bad reputation Many programmers use a subset that avoids some common problems "use strict"; tweaks language to avoid some problematic parts Language being extended to fix things (e.g. ES6, TypeScript) Code quality checkers (e.g. jslint and jshint) widely used 3

Good news if you know C - JavaScript is similar i = 3; i = i * 10 + 3 + (i / 10); while (i >= 0) { sum += i*i; i--; } // Comment for (i = 0; i < 10; i++) { } /* this is a comment */ if (i < 3) { i = foobar(i); } else { i = i *.02; } Most C operators work: * / % + -! >= <= > < &&?: function foobar(i) { return i;} continue/break/return 4

JavaScript has dynamic typing var i; // Need to define variable ('use strict';), note: untyped typeof i == 'undefined' // It does have a type of undefined i = 32; // Now: typeof i == typeof 32 == 'number' i = "foobar"; // Now: typeof i == typeof 'foobar' == 'string' i = true; // Now typeof i == 'boolean' Variables have the type of the last thing assigned to it Primitive types: undefined, number, string, boolean, function, object 5

Variable scoping: Lexical/static scoping Two scopes: Global and function local var globalvar; function() { var localvar; if (globalvar > 0) { var localvar2 = 2; } } All var statements hoisted to top of scope: function foo() { var x; x = 2; // Same as: function foo() { x = 2 var x; 6

Var scope problems Global variables are bad in browsers Easy to get conflicts between modules Hoisting can cause confusion in local scopes function() { for(var i = 0; i < 10; i++) {... for(var i = 0; i < 25; i++) { // Error: i already defined Some JavaScript guides suggest always declaring all var at function start ES6 introduced non-hosting let and explicit scopes 7

number type number type is stored in floating point (i.e. double in C) MAX_INT = (2 53-1) = 9007199254740991 Some oddities: NaN, Infinity are numbers 1/0 == Infinity Math.sqrt(-1) == NaN Nerd joke: typeof NaN returns 'number' Watch out: (0.1 + 0.2) == 0.3 is false // 0.30000000000000004 bitwise operators (e.g. ~, &,, ^, >>, <<, >>>) are 32bit! 8

string type string type is variable length (no char type) var foo = 'This is a test'; // can use "This is a test" foo.length // 14 + is string concat operator foo = foo + 'XXX'; // This is a testxxx Lots of useful methods: indexof(), charat(), match(), search(), replace(), touppercase(), tolowercase(), slice(), substr(), 'foo'.touppercase() // 'FOO' 9

boolean type Either true or false Language classifies values as either truthy or falsy Used when a value is converted to a boolean (e.g. if (foo) { ) Falsy: false, 0, "", null, undefined, and NaN Truthy: Not falsy (all objects, non-empty strings, non-zero numbers, functions, etc.) 10

undefined and null undefined - does not have a value assign var x; // x has a value of undefined x = undefined; // It can be explicitly store typeof x == 'undefined' null - a value that represents whatever the user wants it to Use to return special condition (e.g. no value) typeof null == object Both are falsy but not equal (null == undefined; null!== undefined) 11

function type var foobar = function foobar(x) { // Same as function foobar(x) if (x <= 1) { return 1; } return x*foobar(x-1); } typeof foobar == function ; foobar.name == 'foobar' Function definitions are hoisted (i.e. can use before define) Can be called with variable arguments Array arguments variable (e.g. arguments[0] is first argument) Unspecified arguments have value undefined All functions return a value (default is undefined) 12

First class function example function myfunc(routine) { console.log('called with', routine.tostring()); var retval = routine(10); console.log('retval', retval); } myfunc(function (x) { console.log('called with', x); return x+1; } ); 13

object type Object is an unordered collection of name-value pairs called properties var foo = {}; var bar = {name: "Alice", age: 23, state: "California"}; Name can be any string: var x = { "": "empty", "---": "dashes"} Referenced either like a structure or like a hash table with string keys: bar.name or bar["name"] x["---"] // have to use hash format for illegal names foo.nonexistent == undefined Global scope is an object in browser (i.e. window[prop]) 14

Properties can be added, removed, enumerated To add, just assign to the property: var foo = {}; foo.name = "Fred"; // foo.name returns "Fred" To remove use delete: var foo = {name: "Fred"}; delete foo.name; // foo is now an empty object To enumerate use Object.keys(): Object.keys({name: "Alice", age: 23}) = ["name", "age"] 15

Arrays var anarr = [1,2,3]; Are special objects: typeof anarr == 'object' Indexed by non-negative integers: (anarr[0] == 1) Can be sparse and polymorphic: anarr[5]='foobar'; //[1,2,3,,,'FooBar'] Like strings, have many methods: anarr.length == 3 push, pop, shift, unshift, sort, reverse, splice, Oddity: can store properties like objects (e.g. anarr.name = 'Foo') Some properties have implications: (e.g. anarr.length = 0;) 16

Dates var date = new Date(); Are special objects: typeof date == 'object' The number of milliseconds since midnight January 1, 1970 UTC Timezone needed to convert. Not good for fixed dates (e.g. birthdays) Many methods for returning and setting the data object. For example: date.valueof() = 1452359316314 date.toisostring() = '2016-01-09T17:08:36.314Z' date.tolocalestring() = '1/9/2016, 9:08:36 AM' 17

Regular Expressions var re = /ab+c/; or var re2 = new RegExp("ab+c"); Defines a pattern that can be searched for in a string String: search(), match(), replace(), and split() RegExp: exec() and test() Cool combination of CS Theory and Practice: CS143 Uses: Searching: Does this string have a pattern I m interested in? Parsing: Interpret this string as a program and return its components 18

Regular Expressions by example - search/test /HALT/.test(str); // Returns true if string str has the substr HALT /halt/i.test(str); // Same but ignore case /[Hh]alt [A-Z]/.test(str); // Returns true if str either Halt L or halt L 'XXX abbbbbbc'.search(/ab+c/); // Returns 4 (position of a ) 'XXX ac'.search(/ab+c/); // Returns -1, no match 'XXX ac'.search(/ab*c/); // Returns 4 '12e34'.search(/[^\d]/); // Returns 2 'foo: bar;'.search(/...\s*:\s*...\s*;/); // Returns 0 19

Regular Expressions - exec/match/replace var str = "This has 'quoted' words like 'this'"; var re = /'[^']*'/g; re.exec(str); // Returns ["'quoted'", index: 9, input: re.exec(str); // Returns ["'this'", index: 29, input: re.exec(str); // Returns null str.match(/'[^']*'/g); // Returns ["'quoted'", "'this'"] str.replace(/'[^']*'/g, 'XXX'); // Returns: 'This has XXX words with XXX.' 20

Exceptions - try/catch Error reporting frequently done with exceptions Example: nonexistentfunction(); Terminates execution with error: Uncaught ReferenceError: nonexistentfunction is not defined Exception go up stack: Catch exceptions with try/catch try { nonexistentfunction(); } catch (err) { // typeof err 'object' console.log("error call func", err.name, err.message); } 21

Exceptions - throw/finally Raise exceptions with throw statement try { throw "Help!"; } catch (errstr) { // errstr === "Help!" console.log('got exception', errstr); } finally { // This block is executed after try/catch } Conventions are to throw sub-classes of Error object console.log("got Error:", err.stack err.message err); 22

Getting JavaScript into a web page By including a separate file: <script type="text/javascript" src="code.js"></script> Inline in the HTML: <script type="text/javascript"> //<![CDATA[ Javascript goes here... //]]> </script> 23