Docsity

javascript_programming_language, Slides of Computer Science

Partial preview of the text

Download javascript_programming_language and more Slides Computer Science in PDF only on Docsity!

Mr Oddo

Table of Contents

Preface

Introduction to JavaScript

ECMAScript

ES

ES

ES

ES

Coding style

Lexical Structure

Variables

Types

Expressions

Prototypal inheritance

Classes

Exceptions

Semicolons

Quotes

Template Literals

Functions

Arrow Functions

Closures

Arrays

Loops

Events

The Event Loop

Asynchronous programming and callbacks

Promises

Async and Await

Loops and Scope

Timers

Preface

The JavaScript Handbook follows the 80/20 rule: learn in 20% of the time the 80% of a topic.

I find this approach gives a well-rounded overview. This book does not try to cover everything under the sun related to JavaScript. If you think some specific topic should be included, tell me.

You can reach me on Twitter @flaviocopes.

I hope the contents of this book will help you achieve what you want: learn the basics of JavaScript.

This book is written by Flavio. I publish web development tutorials every day on my website flaviocopes.com.

Enjoy!

Preface

Introduction to JavaScript

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

and now widely used also outside of the browser. The rise of Node.js in the

last few years unlocked backend development, once the domain of Java,

Ruby, Python, PHP, and more traditional server-side languages. Learn all

about it!

Introduction

JavaScript is one of the most popular programming languages in the world.

Created 20 years ago, it's gone a very long way since its humble beginnings.

Being the first - and the only - scripting language that was supported natively by web browsers, it simply stuck.

In the beginnings, it was not nearly powerful as it is today, and it was mainly used for fancy animations and the marvel known at the time as DHTML.

With the growing needs that the web platform demands, JavaScript had the responsibility to grow as well, to accommodate the needs of one of the most widely used ecosystems of the world.

Many things were introduced in the platform, with browser APIs, but the language grew quite a lot as well.

JavaScript is now widely used also outside of the browser. The rise of Node.js in the last few years unlocked backend development, once the domain of Java, Ruby, Python and PHP and more traditional server-side languages.

JavaScript is now also the language powering databases and many more applications, and it's even possible to develop embedded applications, mobile apps, TV sets apps and much more. What started as a tiny language inside the browser is now the most popular language in the world.

A basic definition of JavaScript

JavaScript is a programming language that is:

high level : it provides abstractions that allow you to ignore the details of the machine where it's running on. It manages memory automatically with a garbage collector, so you

Introduction to JavaScript

Currently, the latest approved JavaScript version is ES2017.

Introduction to JavaScript

ECMAScript

ECMAScript is the standard upon which JavaScript is based, and it's often

abbreviated to ES. Discover everything about ECMAScript, and the last

features added in ES6, 7, 8

Whenever you read about JavaScript you'll inevitably see one of these terms:

ES ES ES ES ES ES ES ES ECMAScript 2017 ECMAScript 2016

ECMAScript

What is TC

TC39 is the committee that evolves JavaScript.

The members of TC39 are companies involved in JavaScript and browser vendors, including Mozilla, Google, Facebook, Apple, Microsoft, Intel, PayPal, SalesForce and others.

Every standard version proposal must go through various stages, which are explained here.

ES Versions

I found it puzzling why sometimes an ES version is referenced by edition number and sometimes by year, and I am confused by the year by chance being -1 on the number, which adds to the general confusion around JS/ES ھ

Before ES2015, ECMAScript specifications were commonly called by their edition. So ES5 is the official name for the ECMAScript specification update published in 2009.

Why does this happen? During the process that led to ES2015, the name was changed from ES6 to ES2015, but since this was done late, people still referenced it as ES6, and the community has not left the edition naming behind - the world is still calling ES releases by edition number.

This table should clear things a bit:

Edition Official name Date published ES9 ES2018 June 2018 ES8 ES2017 June 2017 ES7 ES2016 June 2016 ES6 ES2015 June 2015 ES5.1 ES5.1 June 2011 ES5 ES5 December 2009 ES4 ES4 Abandoned ES3 ES3 December 1999 ES2 ES2 June 1998 ES1 ES1 June 1997

ES Next

ECMAScript

ES.Next is a name that always indicates the next version of JavaScript.

So at the time of writing, ES9 has been released, and ES.Next is ES

ECMAScript

Arrow functions since their introduction changed how most JavaScript code looks (and works).

Visually, it's a simple and welcome change, from:

const foo = function foo() { //... }

to

const foo = () => { //... }

And if the function body is a one-liner, just:

const foo = () => doSomething()

Also, if you have a single parameter, you could write:

const foo = param => doSomething(param)

This is not a breaking change, regular function s will continue to work just as before.

A new this scope

The this scope with arrow functions is inherited from the context.

With regular function s this always refers to the nearest function, while with arrow functions this problem is removed, and you won't need to write var that = this ever again.

Promises

Promises (check the full guide to promises) allow us to eliminate the famous "callback hell", although they introduce a bit more complexity (which has been solved in ES2017 with async , a higher level construct).

Promises have been used by JavaScript developers well before ES2015, with many different libraries implementations (e.g. jQuery, q, deferred.js, vow...), and the standard put a common ground across differences.

By using promises you can rewrite this code

ES

setTimeout(function() { console.log('I promised to run after 1s') setTimeout(function() { console.log('I promised to run after 2s') }, 1000) }, 1000)

as

const wait = () => new Promise((resolve, reject) => { setTimeout(resolve, 1000) }) wait().then(() => { console.log('I promised to run after 1s') return wait() }) .then(() => console.log('I promised to run after 2s'))

Generators

Generators are a special kind of function with the ability to pause itself, and resume later, allowing other code to run in the meantime.

The code decides that it has to wait, so it lets other code "in the queue" to run, and keeps the right to resume its operations "when the thing it's waiting for" is done.

All this is done with a single, simple keyword: yield. When a generator contains that keyword, the execution is halted.

A generator can contain many yield keywords, thus halting itself multiple times, and it's identified by the *function keyword, which is not to be confused with the pointer dereference operator used in lower level programming languages such as C, C++ or Go.

Generators enable whole new paradigms of programming in JavaScript, allowing:

2-way communication while a generator is running long-lived while loops which do not freeze your program

Here is an example of a generator which explains how it all works.

function *calculator(input) { var doubleThat = 2 * (yield (input / 2)) var another = yield (doubleThat) return (input * doubleThat * another) }

ES

{ done: true value: 14000 }

As the iteration is done (no more yield keywords found) and we just return (input * doubleThat

  • another) which amounts to 10 * 14 * 100.

let and const

var is traditionally function scoped.

let is a new variable declaration which is block scoped.

This means that declaring let variables in a for loop, inside an if or in a plain block is not going to let that variable "escape" the block, while var s are hoisted up to the function definition.

const is just like let , but immutable.

In JavaScript moving forward, you'll see little to no var declarations any more, just let and const.

const in particular, maybe surprisingly, is very widely used nowadays with immutability being very popular.

Classes

Traditionally JavaScript is the only mainstream language with prototype-based inheritance. Programmers switching to JS from class-based language found it puzzling, but ES introduced classes, which are just syntactic sugar over the inner working, but changed a lot how we build JavaScript programs.

Now inheritance is very easy and resembles other object-oriented programming languages:

class Person { constructor(name) { this.name = name } hello() { return 'Hello, I am ' + this.name + '.' } }

ES

class Actor extends Person { hello() { return super.hello() + ' I am an actor.' } } var tomCruise = new Actor('Tom Cruise') tomCruise.hello()

(the above program prints " Hello, I am Tom Cruise. I am an actor. ")

Classes do not have explicit class variable declarations, but you must initialize any variable in the constructor.

Constructor

Classes have a special method called constructor which is called when a class is initialized via new.

Super

The parent class can be referenced using super().

Getters and setters

A getter for a property can be declared as

class Person { get fullName() { return ${this.firstName} ${this.lastName} } }

Setters are written in the same way:

class Person { set age(years) { this.theAge = years } }

Modules

ES

and strings can span over multiple lines:

const string3 = Hey this string is awesome!

Compare how we used to do multiline strings pre-ES2015:

var str = 'One\n' + 'Two\n' + 'Three'

See this post for an in-depth guide on template literals

Default parameters

Functions now support default parameters:

const foo = function(index = 0, testing = true) { /* ... */ } foo()

The spread operator

You can expand an array, an object or a string using the spread operator ....

Let's start with an array example. Given

const a = [1, 2, 3]

you can create a new array using

const b = [...a, 4, 5, 6]

You can also create a copy of an array using

const c = [...a]

This works for objects as well. Clone an object with:

ES

const newObj = { ...oldObj }

Using strings, the spread operator creates an array with each char in the string:

const hey = 'hey' const arrayized = [...hey] // ['h', 'e', 'y']

This operator has some pretty useful applications. The most important one is the ability to use an array as function argument in a very simple way:

const f = (foo, bar) => {} const a = [1, 2] f(...a)

(in the past you could do this using f.apply(null, a) but that's not as nice and readable)

Destructuring assignments

Given an object, you can extract just some values and put them into named variables:

const person = { firstName: 'Tom', lastName: 'Cruise', actor: true, age: 54, //made up } const {firstName: name, age} = person

name and age contain the desired values.

The syntax also works on arrays:

const a = [1,2,3,4,5] [first, second, , , fifth] = a

Enhanced Object Literals

In ES2015 Object Literals gained superpowers.

Simpler syntax to include variables

ES