Introduction to JavaScript
Niels Olof Bouvin
1
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
Niels Olof Bouvin
1
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
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
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
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
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
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
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
7
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
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
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
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
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
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
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
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
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
(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
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
You can enter the above directly into the Node.js REPL
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
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
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
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
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
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
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
The new method is much cleaner, easier to read, less error-prone, and in all ways superior to the
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
Back in the bad old days, scope (i.e., from where in a program a variable can be seen) was a bit
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
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
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
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
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
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
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
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
Objects can be just fjne as just objects
'use strict' let joe = { name: 'Joe', age: 54,
describe () { return `${this.name} is a ${this.age} years old ${this.occupation}` } } let tom = { ['na' + 'me']: 'Tom', 'Age': 21,
} console.log(joe.name, joe['age']) console.log(joe.describe()) console.log(joe['describe']()) console.log(joe) console.log(tom)
35
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
49
“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
“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
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
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
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
So, you should deal with the results of a computation in the callback function
but what if 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
but don’t worry: there is a better way, and we’ll get back to this problem later
55
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
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