JavaScript Basics, Schemes and Mind Maps of Functional Programming

CS142 Lecture Notes - JavaScript Basics. What is JavaScript? From Wikipedia: ... high-level, dynamic, untyped, and interpreted programming ...

Typology: Schemes and Mind Maps

2021/2022

Uploaded on 09/27/2022

jackie4
jackie4 🇨🇦

4.6

(19)

262 documents

1 / 24

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
CS142 Lecture Notes - JavaScript Basics
JavaScript Basics
Mendel Rosenblum
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18

Partial preview of the text

Download JavaScript Basics and more Schemes and Mind Maps Functional Programming in PDF only on Docsity!

JavaScript Basics

Mendel Rosenblum

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

Good news if you know C - JavaScript is similar

i = 3;

i = i * 10 + 3 + (i / 10);

while (i >= 0) { sum += i*i; // Comment i--; }

for (i = 0; i < 10; i++) {

} /* this is a comment */ (^4)

if (i < 3) { i = foobar(i); } else { i = i * .02; }

Most C operators work:

  • / % + -! >= <= > < && || ?:

function foobar(i) { return i;}

continue/break/return

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

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

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); // Syntax error ... for(let i = 0; i < 10; i++) { let val = "different string"; // Works ● Some JavaScript guides suggest always declaring all var at function start ● ES6 introduced non-hoisting, scoped let and explicit scopes Some coding environments ban var and use let or const instead

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'

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.)

function type

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 definition) ● Can be called with a different number arguments than definition ○ Array arguments variable (e.g. arguments[0] is first argument) ○ Unspecified arguments have value undefined ● All functions return a value (default is undefined)

CS142 Lecture Notes - JavaScript Basics

"First class" function example

let aFuncVar = function (x) { console.log('Func called with', x); return x+1; }; myFunc(aFuncVar); function myFunc(routine) { // passed as a param console.log('Called with', routine.toString()); let retVal = routine(10); console.log('retVal', retVal); return retVal; } 14

Output Called with function (x) { console.log('Called with', x); return x+1; } Func called with 10 retVal 11

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"]

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;)

Regular Expressions

let re = /ab+c/; or let 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: CS

Uses: Searching: Does this string have a pattern I’m interested in? Parsing: Interpret this string as a program and return its components

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