Introduction to JavaScript Niels Olof Bouvin 1 Overview A brief - - PowerPoint PPT Presentation

introduction to javascript
SMART_READER_LITE
LIVE PREVIEW

Introduction to JavaScript Niels Olof Bouvin 1 Overview A brief - - PowerPoint PPT Presentation

Introduction to JavaScript Niels Olof Bouvin 1 Overview A brief history of JavaScript and ECMAScript JavaScript for Java developers The JavaScript ecosystem Getting access to JavaScript Some language basics A look at the Node.js standard


slide-1
SLIDE 1

Introduction to JavaScript

Niels Olof Bouvin

1

slide-2
SLIDE 2

Overview

A brief history of JavaScript and ECMAScript JavaScript for Java developers The JavaScript ecosystem Getting access to JavaScript Some language basics A look at the Node.js standard library

2

slide-3
SLIDE 3

The origins of JavaScript

JavaScript began its life in 1995, when Brendan Eich, working at Netscape, on a deadline created the fjrst version of the language in 10 days

it was originally known as ‘Mocha’ or ‘LiveScript’, but was eventually named ‘JavaScript’ as the Java programming language was very popular at the time

In August 1996, Microsoft debuted JScript, and trying to not lose the initiative, Netscape turned JavaScript

  • ver the ECMA standard organisation

thus, the official name of the language became ECMAScript ECMAScript 1 was standardised in June 1997 the current standard is ES2016, or ES6 for short

3

slide-4
SLIDE 4

JavaScript: backwards compatibility is king

Based on the immense weight of JavaScript code already deployed across the Web, the powers behind JavaScript has sought to maintain compatibility This means that all design decisions of the past, good, bad and worse, are still with us However, if we do not have to maintain a legacy system, we can choose to look and move forward Therefore, we will, in this course, only and exclusively use ES6 and onwards standards, because we are not bound by the bad old days

4

slide-5
SLIDE 5

Overview

A brief history of JavaScript and ECMAScript JavaScript for Java developers The JavaScript ecosystem Getting access to JavaScript Some language basics A look at the Node.js standard library

5

slide-6
SLIDE 6

JavaScript for Java developers

There are many superfjcial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C They are however at heart quite different, and while you certainly will benefjt from your Java knowledge, you should also be aware that this is a new language with a different environments and different rules and conventions

6

slide-7
SLIDE 7

Java vs JavaScript

Object-oriented, class based Statically and strongly typed Compiled Lambdas were only just introduced in Java 8 Requires a JVM to run, rarely seen in browsers these days
 Object-oriented, prototype based Relaxed and dynamically typed Interpreted Functions were always fjrst-class objects Usually either browser

  • r Node.js based

7

slide-8
SLIDE 8

Object-oriented, but different

Java is class-based: Objects are instances of Classes There are no classes in JavaScript, only primitive types and objects. An object may point to another object as its prototype Syntax has been introduced in ES6 to make JavaScript appear more traditionally class-based

as you'll see shortly

8

slide-9
SLIDE 9

Typing

In Java, you defjne what type a variable has, and the compiler will hold you to it In JavaScript, the type is inferred, and you can change your mind without JavaScript complaining, and if you have done something wrong, it will fail when it runs This is a potential minefjeld, so it is important to be disciplined and to use tools to check your code

TypeScript, a superset of JavaScript created by Microsoft, improves on JavaScript by, among other things, adding additional type information

 node > let a = 2 undefined > a 2 > a = '2' '2' > a '2'

9

slide-10
SLIDE 10

Compiled or interpreted

Java is compiled into Bytecode, packing into JAR fjles, and then distributed JavaScript is distributed as text, and interpreted upon delivery There used to be a big performance gap, but that has closed with modern JavaScript engines It means however that the checks made by the Java compiler will fjrst be made when the JavaScript code is interpreted or when it is run

thus, testing quickly becomes really important with JavaScript projects

10

slide-11
SLIDE 11

Objects, functions or both

In Java, everything has to be defjned within a class, whether it makes sense or not In JavaScript, you can just do things, usually through functions, and you can hand functions around like the completely ordinary values they are If you want to use objects and inherit stuff from other stuff, you can do that, too

11

slide-12
SLIDE 12

Overview

A brief history of JavaScript and ECMAScript JavaScript for Java developers The JavaScript ecosystem Getting access to JavaScript Some language basics A look at the Node.js standard library

12

slide-13
SLIDE 13

The JavaScript ecosystem

JavaScript is one of, if not the, most popular programming languages in the world

But, compared to, e.g., Java, JavaScript does not have a strong standard library of functionality ready to use

Thus, an absolute mountain of supporting libraries has been created by thousands and thousands of developers

this is good, because there’s probably a library to solve your problem this is bad, because you may have to wade through dozens if not hundreds of poorly maintained libraries to fjnd The One (or have to choose between multiple valid, fully functioning solutions). It also leads to the “framework of the week” phenomenon

We’ll try to keep things as simple as possible in this course, only including libraries if absolutely necessary

13

slide-14
SLIDE 14

JavaScript ES6

The current standard for ECMAScript It is by now widespread and much nicer than previous versions BUT! Some of the material you’ll encounter (even in this course) will still be using some of the olden ways

I'll try to highlight when I differ from what you have read and I'll usually point to the Eloquent JavaScript book or the MDN site

14

slide-15
SLIDE 15

Overview

A brief history of JavaScript and ECMAScript JavaScript for Java developers The JavaScript ecosystem Getting access to JavaScript Some language basics A look at the Node.js standard library

15

slide-16
SLIDE 16

Getting access to JavaScript

JavaScript is available directly in your Web browser, typically accessed through a ‘Developer’ menu

you may need to explicitly enable this menu

Alternatively, it can installed and used locally through Node.js, which is where we will start

see the Tools page on the course site for installation it can be launched from the command line with ‘node’

16

slide-17
SLIDE 17

Starting out: The JavaScript REPL

(Read, Eval, Print, Loop) If we start node without any arguments, or begin typing in the JavaScript console in a Web browser, we begin in the REPL: Statements are evaluated line by line as they are entered, no compilation necessary

this is a great way to test out code, check proper syntax, or mess with a live Webpage

REPLs are found in most interpreted language, and they are excellent tools, as they allow you to interact directly with your or others’ code

17

slide-18
SLIDE 18

Overview

A brief history of JavaScript and ECMAScript JavaScript for Java developers The JavaScript ecosystem Getting access to JavaScript Some language basics A look at the Node.js standard library

18

slide-19
SLIDE 19

Basic syntax

You can enter the above directly into the Node.js REPL

  • r the JavaScript Console in your browser

try it—it's a good way to get a handle for the syntax and try things out

One statement/expression per line: no need for ;

'use strict' const greeting = 'Hello World' console.log(greeting) const x = 2 if (x < 4) { console.log('x is a small number') } else { console.log('x must be pretty big') }

Beginning a JavaScript program with this line signals to the system that the following is written in the modern, ES6 style. You should always do this—it can catch quite a few errors

19

slide-20
SLIDE 20

Types in JavaScript

Primitive types

boolean number string Symbol

null undefined


Objects

everything else, including the object counterparts: Boolean, Number & String

Wait, what?

this is one of those things considered awful about old design decisions in JavaScript it is a primitive type

> typeof true 'boolean' > typeof 42 'number' > typeof 'hi!' 'string' > typeof null 'object' > typeof undefined 'undefined' > typeof Symbol() 'symbol'

20

slide-21
SLIDE 21

Types are inferred, not declared

You can bind one type of value to a variable, and later bind another type

you shouldn't, but you can. (Don't)

This is one of those things, where tools become useful

> let a = 2 undefined > typeof a 'number' > a = '2' '2' > typeof a 'string' >

21

slide-22
SLIDE 22

What is a number?

Sane programming languages differentiate between integers and fmoating point numbers

in many cases, integers are sufficient and far faster than fmoats

JavaScript engines make a guess of it and usually gets it right

for efficiency's sake, there is now direct support for arrays of specifjc types of numbers, this is very important in, e.g., audio or graphics applications, where performance is crucial

22

slide-23
SLIDE 23

Collections

Arrays, Maps, Sets: should be familiar to Java experts!

> let myList = [1, 2, 3] undefined > myList.length 3 > myList[0] 1 > myList.push(4) 4 > myList [ 1, 2, 3, 4 ] > myList.pop() 4 > myList [ 1, 2, 3 ] > typeof myList 'object' > let myMap = new Map() undefined > myMap.set('a', 'foo') Map { 'a' => 'foo' } > myMap.set('b', 2) Map { 'a' => 'foo', 'b' => 2 } > myMap.set(3, 'a') Map { 'a' => 'foo', 'b' => 2, 3 => 'a' } > myMap.get('a') 'foo' > myMap.has(3) true > let mySet = new Set() undefined > mySet.add('a') Set { 'a' } > mySet.add('b').add('c') Set { 'a', 'b', 'c' } > mySet.add('a') Set { 'a', 'b', 'c' } > mySet.has('b') true

Chainable!

23

slide-24
SLIDE 24

Control statements

Nothing new here, I expect

'use strict' const x = 2 if (x < 4) { console.log('x is a small number') } else { console.log('x must be pretty big') } 'use strict' const myTerm = 'quux' switch (myTerm) { case 'foo': console.log(1) break case 'bar': console.log(2) break case 'baz': console.log(3) break case 'quux': console.log(4) break default: console.log('?') }

24

slide-25
SLIDE 25

Looping and iterating

The basic for loop should be familiar to you for of can iterate through iterables, including Arrays, Maps, and Sets

'use strict' const myPosse = ['Alice', 'Bob', 'Carol'] for (let person of myPosse) { console.log(person) } 'use strict' for (let i = 0; i < 5; i++) { console.log(i) }

25

slide-26
SLIDE 26

Strings and variables, old and new

The new method is much cleaner, easier to read, less error-prone, and in all ways superior to the

  • ld approach

if you can fjnd '`' on your keyboard

'use strict' const first = 'Jane' const last = 'Doe' console.log('Hello ' + first + ' ' + last + '!!') 'use strict' const first = 'Jane' const last = 'Doe' console.log(`Hello ${first} ${last}!`)

26

slide-27
SLIDE 27

var: declaring variable the old way

Back in the bad old days, scope (i.e., from where in a program a variable can be seen) was a bit

  • dd in JS

most programming languages have block scope, but JavaScript had function scope a variable declared with var is scoped within the inner-most function it fjnds itself in, and 'hoisted', i.e., auto-declared from the top of that function

This is an example where having a tool to assist your coding is invaluable

'use strict' var x = 3 function func (randomize) { if (randomize) { var x = Math.random() return x } return x } console.log(func(false))

27

slide-28
SLIDE 28

let & const: the new & improved way

If you use let instead, you get block scoping instead—much easier to handle and understand const is used whenever a variable is not expected to change

it is a good habit to use const whenever possible, because that can catch inadvertent errors the scoping rules are as with let

You should endeavour to always use let and const if at all possible

'use strict' let x = 3 function func (randomize) { if (randomize) { let x = Math.random() return x } return x } console.log(func(false))

28

slide-29
SLIDE 29

let & var, another demonstration

Mixing let and var can lead to confusion, as var declared variables are hoisted to the top of their (functional) context

stick to let and const

'use strict' let x = 10 if (true) { let y = 20 var z = 30 console.log(x + y + z) } console.log(x + z)

29

slide-30
SLIDE 30

Functions

Functions are fjrst-class citizens in JavaScript They can be created, assigned to variables, and passed around as arguments to other functions

'use strict' function myF1 () { return 1 } const myF2 = function () { return 2 } function myFxy (fX, fY) { return fX() + fY() } console.log(myF1(), myF2()) console.log(myFxy(myF1, myF2))

30

slide-31
SLIDE 31

Arguments and default arguments

You can, of course, pass arguments to functions These can have default values, if you wish The … construct allows you to have as many arguments, as you desire

…args must be last

'use strict' function greet (greeting = 'Hi', person = 'friend') { return `${greeting}, ${person}` } function sum (...numbers) { let total = 0 for (let n of numbers) { total += n } return total } console.log(greet()) console.log(greet('Hello')) console.log(greet('Howdy', 'Pardner')) console.log(sum(1, 2, 3, 4, 5, 6, 7, 8, 9))

31

slide-32
SLIDE 32

The arrow function

Functions are used a lot as arguments in JavaScript The => construct makes it easy to create anonymous functions return is implied, but you can add it if you want, including braces

'use strict' const doubler = x => (2 * x) const adder = (x, y) => x + y console.log(doubler(3)) console.log(adder(3, 4)) console.log((x => 3 * x)(3))

32

slide-33
SLIDE 33

Using functions to operate on arrays

Arrays support a number of methods to operate on the entire array, including map, fjlter, and reduce

this can be a very convenient way to, e.g., fjlter an array of strings

This is a place where => functions come into their own

'use strict' const arr = [1, 2, 3, 4] console.log(arr.map(x => 2 * x)) console.log(arr.filter(x => x > 2)) console.log(arr.reduce((acc, c) => acc + c))

33

slide-34
SLIDE 34

Testing for equality

Assignment or binding in JavaScript is '=' '==' used to be the equality operation, but it is badly broken, and you should never use it (it converts type!) '===' and '!==' are the proper operations to use

34

slide-35
SLIDE 35

Old school objects

Objects can be just fjne as just objects

'use strict' let joe = { name: 'Joe', age: 54,

  • ccupation: 'plumber',

describe () { return `${this.name} is a ${this.age} years old ${this.occupation}` } }
 let tom = { ['na' + 'me']: 'Tom', 'Age': 21,

  • ccupation: 'busy'

} console.log(joe.name, joe['age']) console.log(joe.describe()) console.log(joe['describe']()) console.log(joe) console.log(tom)

35

slide-36
SLIDE 36

Old school constructors & inheritance

While there are no classes, objects can have prototypes, and by setting a new object’s prototype, it can be hooked up to an existing object’s prototype, effecting inheritance hierarchies

'use strict' function Person (name, age, job) { this.name = name this.age = age this.job = job this.describe = function () { return `${this.name} is a ${this.age} years old $ {this.job}` } } let fred = new Person('Fred', 50, 'crane operator’) console.log(fred.describe()) Person.prototype.titled = function () { return `${this.job} ${this.name}` } console.log(fred.titled()) console.log(fred instanceof Person)
 function Brony (name, age, job, bestPony) { Person.call(this, name, age, job) this.bestPony = bestPony this.favorite = function () { return `${this.name}'s favorite is ${this.bestPony}` } } Brony.prototype = Object.create(Person.prototype) console.log(Brony.prototype.constructor) Brony.prototype.constructor = Brony let niels = new Brony('Niels', 47, 'associate professor', 'Rarity') console.log(niels.describe()) console.log(niels.favorite()) console.log(Brony.prototype.constructor) console.log(niels instanceof Person) console.log(niels instanceof Brony) console.log(fred instanceof Brony)

36

slide-37
SLIDE 37

Understanding prototype

All objects have a .prototype, and most derive from Object.prototype

Where useful functions, such as toString(), is defjned

If you access a property or call a function on an object, it will fjrst check whether it has it itself, and if not, try its prototype The prototype is just an object, and can be modifjed

so you can actually add new properties and function to ‘super class’ objects

If you want to inherit from an object, you need to hook up to the object’s prototype

37

slide-38
SLIDE 38

Classes and objects in JavaScript ES6

Strictly speaking, classes are also objects in JavaScript ES6, but a bit of syntactic sugar has been introduced to have familiar constructs for most programmers

'use strict' class Point { constructor (x, y) { this.x = x this.y = y } toString () { return `(${this.x}, ${this.y})` } }
 class ColorPoint extends Point { constructor (x, y, color) { super(x, y) this.color = color } toString () { return `${super.toString()} in ${this.color}` } } const cp = new ColorPoint(30, 40, 'green') console.log(cp.toString()) console.log(cp instanceof Point)

38

slide-39
SLIDE 39

Getters and setters

If you are so inclined, it is also possible to create getters and setters in JavaScript

'use strict' class Point { constructor (x, y) { this._x = x this._y = y } toString () { return `(${this.x}, ${this.y})` } get x () { return this._x }
 get y () { return this._y } set x (x) { this._x = x } set y (y) { this._y = y } } const p = new Point(30, 40) console.log(p.toString()) console.log(`p.x = ${p.x}`)

39

slide-40
SLIDE 40

Overview

A brief history of JavaScript and ECMAScript JavaScript for Java developers The JavaScript ecosystem Getting access to JavaScript Some language basics A look at the Node.js standard library

40

slide-41
SLIDE 41

JavaScript does not work in isolation

As we have seen, JavaScript is quite closely integrated into the Web browser, which is exposed through the Document object When it comes to programs outside the browser, JavaScript, in the form of Node.js, relies on its standard library to access the world

such as the fjle system, networking, databases, etc.

41

slide-42
SLIDE 42

JSON: Exchanging data in JavaScript

The predominant format used to transmit data in JavaScript programs is JavaScript Object Notation

it has spread far beyond JavaScript these days used for fjles, and for encoding data to be sent over the Internet

It is quite close to JavaScript in syntax, and be written and read directly It can used to translate arrays and Objects into strings and back again

but curiously enough neither Maps nor Sets, but you’ll fjx that!

42

slide-43
SLIDE 43

The JSON object: stringify() & parse()

The JSON object has two methods: stringify & parse

stringify can take a data structure and return it as a JSON formatted string parse can take a JSON formatted string and return it as a JavaScript object

 node > const myList = [1, 2, 'tre', 4, 'fem'] undefined > myList [ 1, 2, 'tre', 4, 'fem' ] > const myListJSONified = JSON.stringify(myList) undefined > myListJSONified ‘[1,2,”tre",4,"fem"]' > typeof myListJSONified ‘string’ > const myListReturned = JSON.parse(myListJSONified) undefined > myListReturned [ 1, 2, 'tre', 4, 'fem' ] > myListReturned instanceof Array true

43

slide-44
SLIDE 44

Writing to a fjle

Files are important, because they offer persistence JavaScript does not inherently have the ability to deal with fjles

(in truth, it does not have the ability to deal with the outside world at all) this is where the Node.js standard library becomes handy

We will need to use the fjle system module, ‘fs’ for short

44

slide-45
SLIDE 45

Modules

Modules in Node.js are the equivalent of packages in Java

a rich set of objects (classes in Java) that you can use in your programs

In Java, you import a package; in Node.js, we require it Node.js ships with its standard library, and in addition there is an enormous number of third-party modules

45

slide-46
SLIDE 46

Dealing with fjles

Writing to or reading from a fjle is a three stage process:

you open the fjle you write to it, or read from it you close the fjle

Things can go wrong!

perhaps the fjle is not where we expected (or there at all) perhaps we do not have permission to change or read the fjle this calls for exceptions

46

slide-47
SLIDE 47

Writing ‘Hello world’ to a fjle

Isn’t that a lot of code to do just that?

well… yes, but there is a reason, and it has to do with the fundamentals of JavaScript and Node.js interacting with the world

'use strict' const fs = require('fs') const fileName = 'message.txt' fs.open(fileName, 'a', (err, fd) => { if (err) throw err fs.appendFile(fd, 'Hello world!\n', (err) => { fs.close(fd, (err) => { if (err) throw err }) if (err) throw err }) })

47

slide-48
SLIDE 48

What’s with all the arrow functions?

Node.js is a single threaded, non blocking I/O, event- driven system When programs are single threaded, they usually only do one thing at a time, so if they open a fjle, they have to wait for the fjle to be opened (a long time for a computer), while they do nothing (i.e., they freeze) In Node.js, we don’t wait—we start things, and hand them instruction on what to do when they are ready

function are of course a splendid way to give instructions

48

slide-49
SLIDE 49

Doing work in Node.js

One way to think of this is a cashier in a fast-food restaurant receiving orders from customers

some jobs the cashier can do immediately and does so most orders are added to the list (or queue) of things to do for the cooks working behind the counter a cook will take an order off the queue, cook it up, and once fjnished, return the

  • rdered item to the front, where the cashier hands the customer the food

while the cooks are working, the cashier can receive new orders from the customers

We are the customers, dealing with the cashier The cashier leaves, when the queue is empty, the last

  • rder fulfjlled, and all the immediate jobs are done

49

slide-50
SLIDE 50

Opening the fjle

“Open the fjle named fjleName in append mode, and call this function when the fjle is ready or something has gone wrong”

the last argument, the function, is the callback function, and it’s called from fs.open

A callback function often takes two arguments:

an error, and the result of the operation, if there is one

If there is an error, we throw an exception You’ll see this pattern many times in JavaScript

fs.open(fileName, 'a', (err, fd) => { if (err) throw err // . . . })

50

slide-51
SLIDE 51

Opening the fjle

“Append the text ‘Hello world!’ to the fjle identifjed by fd, and call this function when done (or something has gone wrong)”

there is no result returned here, but things can still go wrong, so the callback function still has an err argument, which is set to null if there was no error (and null is false)

Whether the string has been written or not, we need to close the fjle (we know it has been opened) If there was an error with appending the fjle, we throw an error

fs.appendFile(fd, 'Hello world!\n', (err) => { fs.close(fd, (err) => { if (err) throw err }) if (err) throw err })

51

slide-52
SLIDE 52

Reading the fjle back in again

Simpler, but still the same principle:

start something, and give it the instructions on what to do, when ready

'use strict' const fs = require('fs') fs.readFile('message.txt', 'utf8', (err, data) => { if (err) throw (err) console.log(data) })

52

slide-53
SLIDE 53

Will this work?

What is going on here?

'use strict' const fs = require('fs') let theMessage fs.readFile('message.txt', 'utf8', (err, data) => { if (err) throw (err) theMessage = data }) console.log(theMessage)

53

slide-54
SLIDE 54

Let’s add some time to track the code

All the immediate jobs have been done by the cashier

then the cook brings the ordered item to the front

'use strict' const fs = require(‘fs') const start = Date.now() let theMessage fs.readFile('message.txt', 'utf8', (err, data) => { if (err) throw (err) theMessage = data console.log(`File is read: ${Date.now() - start} ms`) console.log(data) }) console.log(theMessage) console.log(`Last line of code: ${Date.now() - start} ms`)

54

slide-55
SLIDE 55

Handling callbacks

So, you should deal with the results of a computation in the callback function

but what if that function also has a callback

  • and that function also has a callback
  • and that function also has a callback
  • and that function also has a callback

Then you are in what in JavaScript is known as ‘callback hell’ and that can be a bit of a mess, because it is hard to keep track of

  • pening and writing to a fjle required three levels of callback—it can be much worse

but don’t worry: there is a better way, and we’ll get back to this problem later

55

slide-56
SLIDE 56

Wrapping up

JavaScript has undergone a tremendous development since its inception, perhaps more than any other Web technology

(it was also in need of some advancement)

Used in its most modern incarnation, ES6, it is a perfectly pleasant language, especially if paired with a bit of tooling to check for potential bugs It is available everywhere you can fjnd a Web browser, and it's easy to get started

56

slide-57
SLIDE 57

Available this Monday

Mobile Pay: 93508374 There are two HDMI displays with keyboard/mouse/ network in the Study Café, and hopefully one soon in Chomsky

Hej labtools Der er nu ankommet 25 kits til Bouvin’s kursus. Det nemmeste ville være at aftale en dag fx. Til en undervisningsgang hvor kits kan sælges. Et kit består af Pi 3+, Case, SD Card(m. Noobs) + strømforsyning. Kan sælges til 350.- samlet for et “kit”

57