Introduction to modern JavaScript

ECA Node/React - June 2019

What is JavaScript?

Web

Client/Server

Give me web page

Web page

Languages

HTML

CSS

JavaScript

Java

PHP

Python

Ruby

Client-side

Server-side

Client-side languages

JavaScript

Interpreted

Popularity of JavaScript

ES6 

2009

"ES2015"

https://kangax.github.io/compat-table/es6/

https://babeljs.io/en/repl.html

Part 1: Basics

Variables

As many other programming languages, data can be stored and used using the notion of variables.

let player = 'Red'
console.log(player + 'has won the match')

We can use one of the three keywords to declare a variable

  1. var, short for "variable", used before ES6.
  2. let introduced with ES6, to be used if the value is meant to be updated.
  3. const, short for "constant", also introduced in ES6.

var vs let

//example with var
for (var i = 0; i < 5; i++) {
  console.log(i)
}
console.log(i)


//example with let
for (let j = 0; j < 5; j++) {
  console.log(j)
}
console.log(j)

We don't advise to use var because it is function-scoped which may lead to confusion.

Const and let on the other hand are block-scoped

const

As a good practice, prefer const over let unless you want your variable to be reassigned.

const pokemon = {
  name: 'pikachu',
  attack: 100,
  defense: 80,
  speed: 110,
  moves: ['thunder', 'surf', 'fly'],
}

pokemon.name='raichu'
console.log(pokemon)

const does not mean immutable ! It only means, it cannot be reassigned !

Objects

const red = {
    name: "red",
    badges: 3,
    pokemons: ["pikachu", "rondoudou", "canarticho"]
}

console.log(red);

//you can access a property by using the dot notation
console.log(red.name);

Objects allow us to group values — including other objects — to build more complex structures.

Arrays

An Array is a dataset used specifically for storing sequences of values. It is called an array and is written as a list of values between square brackets, separated by commas.

const pokemons = ['pikachu', 'racaillou', 'carapuce']

console.log(pokemons)

//the first element is at the index 0
console.log(pokemons[0])

//the last element can be accessed using the property length-1
console.log(pokemons[pokemons.length-1])

Functions

A function is a reusable piece of code you can call several times in your program.

const square = function(x) {
    return x * x
}
console.log(square(12)) // → 144

A function is created with an expression that starts with the keyword function. Between parenthesis are the list of parameters separated by commas.

Arrow functions

const level = (experience, coefficient) => {
    return coefficient * experience / 500
}

// if it is a single expression, braces and the return keyword can be omitted
const level2 = (experience, coefficient) => coefficient * experience / 500


console.log(level(100, 1))
console.log(level2(100, 1))

if {} else {}

let number = 0
if (number < 0) {
    console.log("Number is negative")
} else if (number > 0){
    console.log("Number is positive")
} else {
    console.log("Number is 0") //Number is 0
}
number > 0 ? "Number is positive" : "Number is negative" 

Loops

let number = 0; 
while (number <= 12) {
    console.log(number)
    number = number + 2
}

for (let number = 0; number <= 12; number = number + 2) {
    console.log(number)
}

Part 2: ES6

Template literals

// ES5
const sentence = "My favorite pokemon is " + pokemon + "!"

// ES6
const sentence = `My favorite pokemon is ${pokemon}!`


Destructuring

Array destructuring

const badges = ["Boulder", "Cascade", "Thunder", "Rainbow", "Soul", "Marsh", "Volcano", "Earth"]

// ES5
const thirdBadge = badges[2]
const sixthBadge = badges[5]
const seventhBadge = badges[6]

// ES6
const [,,thirdBadge,,,sixthBadge,seventhBadge,] = badges

Object destructuring

const pokemonTrainer = {
 name: "Red",
 badges: 8,
 city: "Pallet Town",
 favoritePokemon: "Pikachu"
}


/* Example 1 */

// ES5
const name = pokemonTrainer.name
const badges = pokemonTrainer.badges
const favoritePokemon = pokemonTrainer.favoritePokemon

// ES6
const { name, badges, favoritePokemon } = pokemonTrainer


/* Example 2: alias */

// ES5
const firstName = pokemonTrainer.name
const badges = pokemonTrainer.badges

// ES6
const { name: firstName, badges } = pokemonTrainer

Object destructuring

const pokemonTrainer = {
 name: "Red",
 badges: 8,
 city: "Pallet Town",
 favoritePokemon: "Pikachu"
}


/* Example 3 */

// Without destructuring
const displayInfo = (trainer) => {
 console.log( `${ trainer.name } lives in ${ trainer.city } and his favorite Pokemon is ${ trainer.favoritePokemon }`)
}

// With destructuring
const displayInfo = ({name, city, favoritePokemon}) => {
 console.log( `${ name } lives in ${ city } and his favorite Pokemon is ${ favoritePokemon }`)
}

Rest/Spread

// Rest operator

function bestPokemons(first, second, ...others) {
    return {
        first, second, others
    }
}

JSON.stringify(bestPokemons('pikachu', 'bulbizarre', 'pokemon1', 'pokemon2')) 
// {"first":"pikachu","second":"bulbizarre","others":["pokemon1","pokemon2"]}


// Spread (array and object)

// Copy an array
const pokemons = ['pikachu', 'bulbizarre']
const pokemonsCopy = [...pokemons]
JSON.stringify(pokemonsCopy)
// ["pikachu","bulbizarre"]

// Copy an object
const pokemon = {name: 'pikachu', attack: 100, defense: 50}
const clonedPokemon = {...pokemon, name: 'cloned pikachu'}
JSON.stringify(clonedPokemon)
// {"name":"cloned pikachu","attack":100,"defense":50}

Syntax

// Merge 2 arrays

// ES5
var pokemons = ['Pikachu', 'Bulbizarre']
var rocketTeam = ['Miaouss', 'Racaillou']


var all = pokemons.concat(rocketTeam)
// or
var all = Array.prototype.concat.apply(pokemons, rocketTeam)


// ES6
const all = [...pokemons, ...rocketTeam]


// Merge 2 objects

// ES5
var pikachu = {name: 'Pikachu'}
var superStats = {attack: 100, defense: 100}

var superPikachu = Object.assign({}, pikachu, superStats)

// ES6
const superPikachu = {...pikachu, ...superStats}

ES5 vs ES6

Class

class Rectangle {
  constructor(height, width) {
    this.name = 'Rectangle'
    this.height = height
    this.width = width
  }
  sayName() {
    console.log(
      // here this references to the caller
      `Hi I am a ${this.name} with height ${this.height}, width ${this.width}.`
    )
  }
  get area() {
    return this.height * this.width
  }
  set area(value) {
    this.height = this.width = Math.sqrt(value)
  }
}

// extends is possible
class Square extends Rectangle {
  constructor(length) {
    super(length, length)
    this.name = 'Square'
  }

  sayName() {
    super.sayName()
    console.log(`Square talks too much`)
  }
}

Higher-order functions

Array function (Lambda)

['pikachu', 'carapuce', 'miaouss'].forEach(p => console.log(p)) // data iteration
['pikachu', 'carapuce', 'miaouss'].filter(p => p.length < 8) // data filtering
['pikachu', 'carapuce', 'miaouss'].map(p => `pokemon ${p}`) // data transformation

['pikachu', 'carapuce', 'miaouss']
	.filter(p => p.length < 8)
	.map(p => `pokemon ${p}`)
	.forEach(p => console.log(p)) // composability

Lab time!

See you next week!

Introduction to modern JavaScript

By yagong

Introduction to modern JavaScript

ECA Node/React - November 7th 2018

  • 754