Download JavaScript Basics and more Schemes and Mind Maps Functional Programming in PDF only on Docsity! CS142 Lecture Notes - JavaScript Basics JavaScript Basics Mendel Rosenblum 1 CS142 Lecture Notes - JavaScript Basics 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 CS142 Lecture Notes - JavaScript Basics 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 CS142 Lecture Notes - JavaScript Basics Variable scoping with var: Lexical/static scoping Two scopes: Global and function local var globalVar; function foo() { var localVar; if (globalVar > 0) { var localVar2 = 2; } // localVar2 is valid here } 6 All var statements hoisted to top of scope: function foo() { var x; x = 2; // Same as: function foo() { x = 2 var x; localVar2 is hoisted here but has value undefined CS142 Lecture Notes - JavaScript Basics Var scope problems ● Global variables are bad in browsers - Easy to get conflicts between modules ● Hoisting can cause confusion in local scopes (e.g. access before value set) function() { console.log('Val is:', val); ... for(var i = 0; i < 10; i++) { var val = "different string"; // Hoisted to func start ● Some JavaScript guides suggest always declaring all var at function start ● ES6 introduced non-hoisting, scoped let and const with explicit scopes Some coding environments ban var and use let or const instead 7 CS142 Lecture Notes - JavaScript Basics string type string type is variable length (no char type) let 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' 10 CS142 Lecture Notes - JavaScript Basics 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, NaN, "", undefined, and null ● Truthy: Not falsy (all objects, non-empty strings, non-zero/NaN numbers, functions, etc.) 11 CS142 Lecture Notes - JavaScript Basics undefined and null ● undefined - does not have a value assign let 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) 12 CS142 Lecture Notes - JavaScript Basics object type ● Object is an unordered collection of name-value pairs called properties let foo = {}; let bar = {name: "Alice", age: 23, state: "California"}; ● Name can be any string: let 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]) 15 CS142 Lecture Notes - JavaScript Basics Properties can be added, removed, enumerated ● To add, just assign to the property: let foo = {}; foo.name = "Fred"; // foo.name returns "Fred" ● To remove use delete: let 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"] 16 CS142 Lecture Notes - JavaScript Basics Arrays let 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;) 17 CS142 Lecture Notes - JavaScript Basics 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 20 CS142 Lecture Notes - JavaScript Basics Regular Expressions - exec/match/replace let str = "This has 'quoted' words like 'this'"; let 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.' 21 CS142 Lecture Notes - JavaScript Basics 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); } 22