54
Introduction to JavaScript Niels Olof Bouvin 2

Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

  • Upload
    others

  • View
    2

  • Download
    1

Embed Size (px)

Citation preview

Page 1: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

Introduction to JavaScriptNiels Olof Bouvin

2

Page 2: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

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

3

Page 3: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

The origins of JavaScript

JavaScript began its life in 1995, when Brendan Eich, working at Netscape, on a deadline created the first 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 over 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

4

Page 4: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

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

5

Page 5: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

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

6

Page 6: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

JavaScript for Java developers

There are many superficial 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 benefit from your Java knowledge, you should also be aware that this is a new language with a different environments and different rules and conventions

7

Page 7: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

Java vs JavaScript

Object-oriented, class based design

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, relaxed, prototype based

Relaxed and dynamically typed

Interpreted

Functions were always first-class objects

Usually either browser or Node.js based

8

Page 8: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

Object-oriented, but different

Java is class-based: Objects are instances of Classes

There are no classes in JavaScript per se, only primitive types and objects. An object may point to another object as its prototype

The Java approach of defining class hierarchies for development is foreign to JavaScript

Syntax has been introduced in ES6 to make JavaScript appear more traditionally class-based

as you'll see shortly

9

Page 9: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

Typing

In Java, you define 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 minefield, 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'

10

Page 10: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

Compiled or interpreted

Java is compiled into Bytecode, packed into JAR files, 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 first be made when the JavaScript code is interpreted or when it is run

thus, testing quickly becomes really important with JavaScript projects

11

Page 11: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

Objects, functions or both

In Java, everything has to be defined 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

12

Page 12: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

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

13

Page 13: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

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 find 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

14

Page 14: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

JavaScript ES6 and onwards

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

15

Page 15: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

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

16

Page 16: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

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 somewhere in ‘Settings’ or ‘Preferences’

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’

17

Page 17: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

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 languages, and they are excellent tools, as they allow you to interact directly with your or others’ code

18

Page 18: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

Following along

I would like you to follow along with the code, so download the zip-file, open VSC, load the files, open the terminal (View→Terminal), and run the code using node You should also know that the code examples in the Eloquent JavaScript book are also interactive—please use it, it is a great learning tool

19

Page 19: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

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

20

Page 20: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

Basic syntax

You can enter the above directly into the Node.js REPL or 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;

'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

21

Page 21: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

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'

22

Page 22: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

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. (Please do not)

This is one of those things, where tools become useful

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

23

Page 23: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

What is a number?

Sane programming languages differentiate between integers and floating point numbers

in many cases, integers are sufficient, faster, and more compact than floats

Yet, JavaScript knows only Numbers, which are floats

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

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

24

Page 24: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

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!

25

Page 25: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

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('?'); }

26

Page 26: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

Looping and iterating

The basic for loop should be familiar to you

for of can iterate through iterables, including Arrays, Maps, and Sets, and is in general the preferred version of for

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

27

Page 27: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

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 old approach

if you can find '`' 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}!`);

28

Page 28: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

var: declaring variable the old wayBack in the bad old days, scope (i.e., from where in a program a variable can be seen) was a bit odd 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 finds 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));

29

Page 29: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

let & const: the new & improved wayIf 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));

30

Page 30: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

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

31

Page 31: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

Functions

Functions are first-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));

32

Page 32: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

Arguments and default argumentsYou 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));

33

Page 33: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

The arrow functionFunctions 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

Functions can also just be created in situ

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

34

Page 34: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

Using functions to operate on arrays

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

this can be a very convenient way to, e.g., filter 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));

35

Page 35: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

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 use36

Page 36: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

Classes and objects in JavaScript ES6

Strictly speaking, classes are functions 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);

37

Page 37: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

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

38

Page 38: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

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

39

Page 39: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

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 file system, networking, databases, etc.

40

Page 40: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

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 files, and for encoding data to be sent over the Internet

It is quite close to JavaScript in syntax, and can 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 fix that!

41

Page 41: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

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

42

Page 42: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

Writing to a file

Files are important, because they offer persistence

JavaScript does not inherently have the ability to deal with files

(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 file system module, ‘fs’ for short

43

Page 43: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

Modules

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

a rich set of objects and functions (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

44

Page 44: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

Dealing with files

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

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

Things can go wrong! perhaps the file is not where we expected (or there at all) perhaps we do not have permission to change or read the file perhaps something goes wrong as we are reading or writing this calls for exceptions

45

Page 45: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

Writing ‘Hello world’ to a file

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', 'utf8', (err) => { fs.close(fd, (err) => { if (err) throw err; }); if (err) throw err; }); });

46

Page 46: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

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 file, they have to wait for the file 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

47

Page 47: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

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 finished, return the ordered 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 order fulfilled, and all the immediate jobs are done

48

Page 48: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

Opening the file

“Open the file named fileName in append mode, and call this function when the file 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; // . . . })

49

Page 49: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

Opening the file

“Append the text ‘Hello world!’ to the file identified 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 file (we know it has been opened)

If there was an error with appending the file, we throw an error

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

50

Page 50: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

Reading the file 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); // handle any errors console.log(data); // do the thing })

51

Page 51: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

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

52

Page 52: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

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

53

Page 53: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

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

opening and writing to a file 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

54

Page 54: Introduction to JavaScript · JavaScript for Java developers There are many super!cial similarities between Java and JavaScript, as they, syntax-wise, share a common ancestor in C

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 find a Web browser, and it's easy to get started

55