Data

Data type

  • Strings=console.log(‘Newark city); 
  • Numbers=console.log(50.3); 
  • Booleans=console.log(true); 
  • Null=console.log(null);     ( It represents the absence of value.)

Math Operators

  • Add: +
  • Subtract: - 
  • Multiply: *
  • Divide: /
  • Modulo: %

Properties

console.log('Hello'.length);

Built-in Methods

console.log('Hello'.toUpperCase()); // 'HELLO'
console.log('Hey'.startsWith('H')); // true
console.log('    Remove whitespace   '.trim());

Librairies

console.log(Math.floor(Math.random() * 100));
console.log(Math.ceil(43.8));
console.log(Number.isInteger(2017));

Comments

// Ceci est un commentaire
/* Ceci est un autre commentaire */


Introduction to Control Flow

if/else Statements

let isSoccerFan = true;

   if (isSoccerFan === true) {
   console.log("Goal!");
} else {
   console.log("No goal!");
}

True and False Values

  • false
  • 0 and -0
  • "" and '' (empty strings)
  • null
  • undefined
  • NaN (Not a Number)
  • document.all (something you will rarely encounter)

True and False Values II

let favoritePhrase = '1';

   if (!favoritePhrase) {
   console.log("This string doesn't seem to be empty.");
} else {
  console.log('This string is definitely empty.');
}

Comparaisons Operators

Less than: <
Greater than: >

You may also recognize these:

Less than or equal to: <=
Greater than or equal to: >=

These comparisons evaluate to true or false.

let hungerLevel = 10;

if (hungerLevel > 7) {
    console.log("Time to eat!");
    } else {
    console.log("We can eat later!");  
}

Comparaisons Operators II

  • To check if two things equal each other, we write === (three = signs in a row).
  • To check if two things do not equal each other, we write !== (an exclamation with two = signs in a row).

It can be confusing when to use one = sign and when to use three === signs. Use a single = to assign a value to a variable.
Use === to compare the values of two different variables.

Else if Statement

let stopLight = 'green';

if (stopLight === 'red') {
  console.log('Stop');
} else if (stopLight === 'yellow') {
  console.log('Slow down');
} else if (stopLight === 'green') {
  console.log('Go!');
} else {
  console.log('Caution, unknown!');
}

Logicals Operators

  • To say "both must be true," we use &&.
  • To say "either can be true," we use ||.

L’operator &&

if (stopLight === 'green' && pedestrians === false) {
  console.log('Go!');
} else {
  console.log('Stop');
}

L’operator ||

let moonPhase = "full";

let isFoggyNight = false;

if (moonPhase === "full" || isFoggyNight === true ) {

    console.log("Howl!");

    } else if (moonPhase === "mostly full") {

    console.log("Arms and legs are getting hairier");

    } else if (moonPhase === "mostly new") {

    console.log("Back on two feet");

    } else {

       console.log("Invalid moon phase");
    }

Switch Statements

let groceryItem = 'papaya';

switch (groceryItem) {

  case 'tomato':
    console.log('Tomatoes are $0.49');
    break;

  case 'lime':
    console.log('Limes are $1.49');
    break;

  case 'papaya':
    console.log('Papayas are $1.29');
    break;

  default:
    console.log('Invalid item');
    break;
}

Ternary Operator

isNightTime ? console.log('Turn on the lights!') : console.log('Turn off the lights!');

let isLocked = false;

isLocked ? console.log('You will need a key to open the door.') : console.log('You will not need a key to open the door.');

let isCorrect = true;

isCorrect ? console.log('Correct!') : console.log('Incorrect!');

let favoritePhrase = 'Love That!';

favoritePhrase === 'Love That!' ? console.log('I love that!') : console.log("I don't love that!");


Introduction to Functions

Functions ES5

function myFunction(p1, p2) {
    return p1 * p2;
}
console.log(myFunction(4, 3));

Functions ES6

// Same function but in es6

const myFunction = (p1, p2) => p1 * p2;
console.log(myFunction(4, 3));

…an other one…

let calculatorIsOn = false;

const pressPowerButton = () => {
  if (calculatorIsOn) {
    console.log('Calculator turning off.');
    calculatorIsOn = false;
  } else {
    console.log('Calculator turning on.');
    calculatorIsOn = true;
  }
};

pressPowerButton();
// Output: Calculator turning on.

pressPowerButton();
// Output: Calculator turning off.

Parameters

function multiplyByThirteen(inputNumber) {
  console.log(inputNumber * 13);
}

multiplyByThirteen(9);
// Output: 117

or

const multiplyByThirteen = (inputNumber) => {
  console.log(inputNumber * 13);
};

multiplyByThirteen(9);

// Output: 117

Personnal note:

const nameFunction = (parameter) => {
  console.log(parameter * 13);
};

multiplyByThirteen(argument pass to parameter);

Parameters II

const getAverage = (numberOne, numberTwo) => {
  const average = (numberOne + numberTwo) / 2 ;
  console.log(average);
};

getAverage(365, 27);
// Output: 196

Return

const getAverage = (numberOne, numberTwo) => {
  const average = (numberOne + numberTwo) / 2;
  return average;
}
console.log(getAverage(365, 27));
// Output: 196

or

let orderCount = 0;
const takeOrder = (topping, crustType) => {
  orderCount++;
  console.log('Order: ' + crustType + ' pizza topped with ' + topping);
};

takeOrder('mushroom', 'thin crust');
takeOrder('spinach', 'whole wheat');
takeOrder('pepperoni', 'brooklyn style');

const getSubTotal = (itemCount) => {
  return itemCount * 7.5;
};
console.log(getSubTotal(orderCount));

Return II

const getAverage = (numberOne, numberTwo) => {
  const average = (numberOne + numberTwo) / 2;
  return average;
}
console.log(getAverage(365, 27));
// Output: 196

or

// Initialize count to zero

let orderCount = 0;

// Create order
const takeOrder = (topping, crustType) => {
  orderCount++;
  console.log('Order: ' + crustType + ' pizza topped with ' + topping);
};

// Call the order

takeOrder('mushroom', 'thin crust');
takeOrder('spinach', 'whole wheat');
takeOrder('pepperoni', 'brooklyn style');

// Calculate number of pizza
const getSubTotal = (itemCount) => {
  return itemCount * 7.50;
};
// Calculate the tax to all items
const getTax = () => {
  return getSubTotal(orderCount) * 0.06;
};

// Calculate total pizza + tax
const getTotal = () => {
  return getSubTotal(orderCount) + getTax();
};

console.log(getSubTotal(orderCount)+ ' total');
console.log(getTax());
console.log(getTotal());

Function Declarations

function square (number) {
  return number * number;
}
console.log(square(5));
// Output: 25.

Function Expressions

const square = function (number) {
  return number * number;
};
console.log(square(5));
// Output: 25.

or arrow function

const square = (number) => {
  return number * number;
};
console.log(square(5));
// Output: 25.

or arrow function (concise body / implicit return)

const square = number => number * number;
console.log(square(5));
// Output: 25.

  • Functions that take a single parameter should not use parentheses. The code will still work, but it's better practice to omit the parentheses around single parameters. However, if a function takes zero or multiple parameters, parentheses are required.
  • A function composed of a sole single-line block is automatically returned. The contents of the block should immediately follow the arrow => and the return keyword can be removed. This is referred to as implicit return.
  • A function composed of a sole single-line block does not need brackets.

Introduction to Scope

Global Scope

const color = 'blue'
const colorOfSky = () => {
return color; // blue
};
console.log(colorOfSky()); // blue

Global Scope II

const satellite = 'The Moon';
const galaxy = 'The Milky Way';

let stars = 'North Star';
const myNightSky = () => {
  stars = 'Sirius';
  return 'Night Sky: ' + satellite + ', ' + stars + ', ' + galaxy;
}
console.log(myNightSky());
console.log(stars);

Block Scope 

Block scope means that a variable defined in the block is only accessible within the curly braces.

const colorOfSky = () => {
  let color = 'blue';
  console.log(color); // blue
};

colorOfSky(); // blue
console.log(color); // undefined

Block Scope II

const colorOfSky = () => {
  const dusk = true;
  let color = 'blue';
  if (dusk) {
    let color = 'pink';
    console.log(color); // pink
  }
  console.log(color); // blue
};
colorOfSky(); // blue
console.log(color); // undefined

Block Scope III

const cloudCount = () => {
  let i = 2;
  console.log(i); // 2
for (let i = 0; i < 10; i++) {
console.log(i); // All numbers from 0 to 9
  }
};
cloudCount();
console.log(i); // undefined


Arrays

Create an array

let newYearsResolutions = ['
Rappel into a cave', 'Take a falconry class', 'Learn to juggle'
];

Property Access

for an array

let newYearsResolutions = ['Rappel into a cave', 'Take a falconry class', 'Learn to juggle'];
console.log(newYearsResolutions[0]);
// Output: 'Rappel into a cave'

for a string

let hello = 'Hello World';
console.log(hello[6]);
// Output: W

Update Elements

const newYearsResolutions = ['ete', 'automne', 'hiver', 'printemps'];
console.log(newYearsResolutions);

newYearsResolutions[0] = 'Party';
console.log(newYearsResolutions);

Length property

let newYearsResolutions = ['
Rappel into a cave', 'Take a falconry class
'];
console.log(newYearsResolutions.length);
// Output: 2

Push Method

.push() allows us to add items to the end of an array:

let newYearsResolutions = ['item 0', 'item 1', 'item 2'];
newYearsResolutions.push('item 3', 'item 4');
// output ['item 0', 'item 1', 'item 2', 'item 3', 'item 4'];

Pop Method

.pop() This method removes the last item of an array.

let newYearsResolutions = ['
item 0', 'item 1', 'item 2'
];

newYearsResolutions.pop();
console.log(newYearsResolutions);
// Output: [ 'item 0', 'item 1' ]

More Array Methods

Some methods that JavaScript developers use frequently are .join(), .slice(), .splice(), .shift(), .unshift(), and .concat() amongst many others.

Arrays with let and const

function blocky() {
  const something = 'Something';

  if(true) {
    let something = 'Something2';
    console.log(something);
  }

  something = 'Somethingnew';
  console.log(something);
}
blocky();


Loops

There are two kinds of loops we will learn in this lesson:
for loops, which let us loop a block of code a known amount of times.
while loops, which let us loop a block of code an unknown amount of times.

for Loops

let animals = ["Grizzly Bear", "Sloth", "Sea Lion"];

for (let animalIndex = 0; animalIndex < animals.length; animalIndex++) {
  console.log(animals[animalIndex]);
}

for Loops, Backwards

let vacationSpots = ['Mexico', 'Italie', 'France'];

for (let vacationSpotIndex = vacationSpots.length - 1; vacationSpotIndex >= 0; vacationSpotIndex--) {
  console.log('I would love to visit ' + vacationSpots[vacationSpotIndex]);
}

Nested for Loops

// Loop inside an other loop

let myPlaces = [ 'Paris1', 'Italie', 'Irlande' ];
let friendPlaces = [ 'Matane', 'Boston', 'Paris2' ];
for (let myPlacesIndex = 0; myPlacesIndex < myPlaces.length; myPlacesIndex++ ) {
  console.log(myPlaces[myPlacesIndex]);
  for (let friendPlacesIndex = 0; friendPlacesIndex < friendPlaces.length; friendPlacesIndex++ ) {
  console.log(friendPlaces[friendPlacesIndex]);
  }
}

while Loops

let cards = ['Diamond', 'Spade', 'Heart', 'Club'];
let currentCard = 'Shuffle the card';

while (currentCard !== 'Spade') {
       console.log(currentCard);
   currentCard = cards[Math.floor(Math.random() * 4)];
       }
console.log('found a spade')


Introduction to Iterators

.forEach()

let artists = ['Picasso', 'Kahlo', 'Matisse', 'Utamaro'];

artists.forEach(function(artist) {
console.log(artist + ' is one of my favorite artists.');
});

or

let groceries = ['whole wheat flour', 'brown sugar', 'salt', 'cranberries', 'walnuts']; 

groceries.forEach(function(groceryItem) {
  console.log(' - ' + groceryItem);
});

or ES6

let groceries = ['whole wheat flour', 'brown sugar', 'salt', 'cranberries', 'walnuts']; 

groceries.forEach(groceryItem => console.log(' - ' + groceryItem));

.map() 

Return new array

let numbers = [1, 2, 3, 4, 5];

let squareNumbers = numbers.map(function(number) {
  return number * number;
});

console.log(squareNumbers);

or

let animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];

// Create the secretMessage array below

let secretMessage = animals.map(animal => animal.charAt(0));

console.log(secretMessage.join(''));

.filter() 

Return new array

let things = ['desk', 'chair', 5, 'backpack', 3.14, 100];
let onlyNumbers = things.filter(function(thing) {
  return typeof thing === 'number';
});
console.log(onlyNumbers);

or

let words = ['chair', 'music', 'pillow', 'brick', 'pen', 'door'];
let shortWords = words.filter(function(word) {
  return word.length < 5;
});
console.log(shortWords);


Introduction to Javascript Objects

Objects

JavaScript objects are containers that can store data and functions. The data we store in an object is not ordered — we can only access it by calling its associated key.

let restaurant = {
  name: 'Italian Bistro',
  seatingCapacity: 120,
  hasDineInSpecial: true,
  entrees: ['Penne alla Bolognese', 'Chicken Cacciatore', 'Linguine Pesto']
};

Accessing Object Properties I

let person = {
  name: 'Nico',
  age: 40
};
console.log(person.name);
console.log(person.age);

Accessing Object Properties II

let person = {
  name: 'Nico',
  age: 40
};
console.log(person['name'];
console.log(person['age'];

Accessing Object Properties III

let meal = 'none';
let time = 12;

// We'll use military time for this example, counting hours 0-23.

const restaurantSpecials = {
 breakfast: 'The breakfast special is 20% off freshly squeezed orange juice',
 lunch: 'The lunch special is 10% off appetizers',
 none: 'There are no specials currently'
};

if (time < 11) { // 11 am
  meal = 'breakfast';
} else if (time < 17) { // 5 pm
  meal = 'lunch';
}
console.log(restaurantSpecials[meal]);

Adding a Property

const restaurant = {
  name: 'Italian Bistro',
  seatingCapacity: 120,
  hasDineInSpecial: true,
  entrees: ['Penne alla Bolognese', 'Chicken Cacciatore', 'Linguine pesto']
}
console.log(restaurant);

restaurant.desserts = ['Homemade Tiramisu', 'Cannoli'];
console.log(restaurant);

restaurant['appetizers'] = ['Fried Calamari', 'Bruschetta'];
console.log(restaurant);

Editing a Property

restaurant['appetizers'] = ['Fried Calamari', 'Bruschetta', 'Caprese Salad'];
restaurant.desserts = ['Homemade Tiramisu', 'Canolli', 'Cheesecake'];

Methods

const restaurant = {
  name: 'Italian Bistro',
  seatingCapacity: 120,
  hasDineInSpecial: true,
  entrees: ['Penne alla Bolognese', 'Chicken Cacciatore', 'Linguine pesto'],
  openRestaurant: () => {
    return 'Unlock the door, flip the open sign. We are open for business!';
  },
  closeRestaurant: () => {
    return 'Lock the door, flip the open sign. We are closed.'
  }
};
console.log(restaurant.openRestaurant());
console.log(restaurant.closeRestaurant());

Methods: ES6

const restaurant = {
  name: 'Italian Bistro',
  seatingCapacity: 120,
  hasDineInSpecial: true,
  entrees: ['Penne alla Bolognese', 'Chicken Cacciatore', 'Linguine pesto'],
  openRestaurant() {
    return 'Unlock the door, flip the open sign. We are open for business!';
  },

  closeRestaurant() {
    return 'Lock the door, flip the open sign. We are closed.'
  }
}
console.log(restaurant.openRestaurant());
console.log(restaurant.closeRestaurant());

The this Keyword I

const restaurant = {
  name: 'Italian Bistro',
  seatingCapacity: 120,
  hasDineInSpecial: true,
  entrees: ['Penne alla Bolognese', 'Chicken Cacciatore', 'Linguine pesto'],
  openRestaurant() {

       if (this.hasDineInSpecial) {
      return 'Unlock the door, post the special on the board, then flip the open sign.';
    } else {
      return 'Unlock the door, then flip the open sign.';
    }
  }
};
console.log(restaurant.openRestaurant());

The this Keyword II

let myObj = {
  name: 'Miti',
  sayHello() {
    return `${this.name} says hello!`;
  }
};

let yourObj = {
  name: 'Timer'
};
yourObj.sayHello = myObj.sayHello;
console.log(yourObj.sayHello());

Getters and Setters I

let person = {
  _name: 'Lu Xun',
  _age: 137,

  set age(ageIn) {
    if (typeof ageIn === 'number') {
      this._age = ageIn;
    }
    else {
      console.log('Invalid input');
      return 'Invalid input';
    }
  }
};

Getters and Setters II

let person = {
  _name: 'Lu Xun',
  _age: 137,

    set age(ageIn) {

    if (typeof ageIn === 'number') {
      this._age = ageIn;
    }  else {
      console.log('Invalid input');
      return 'Invalid input';
    }
  }
};
person.age = 'Thirty-nine';
person.age = 39;

or

let restaurant = {
  _name: 'Italian Bistro',
  _seatingCapacity: 120,
  _hasDineInSpecial: true,
  _entrees: ['Penne alla Bolognese', 'Chicken Cacciatore', 'Linguine pesto'],

  set seatingCapacity(newCapacity) {
     if (typeof newCapacity === 'number') {
        this._seatingCapacity = newCapacity;
       console.log(`${newCapacity} is valid input.`);
    } else {
        console.log(`Change ${newCapacity} to a number.`);
    }
  }
}
restaurant.seatingCapacity = 150;

Getters and Setters III

let restaurant = {
  _name: 'Italian Bistro',
  _seatingCapacity: 120,
  _hasDineInSpecial: true,
  _entrees: ['Penne alla Bolognese', 'Chicken Cacciatore', 'Linguine pesto'],

  set seatingCapacity(newCapacity) {
    if (typeof newCapacity === 'number') {
      this._seatingCapacity = newCapacity;
    } else {
      console.log(`Change ${newCapacity} to a number.`)
    }
  },

  get seatingCapacity() {
    console.log(`There are ${this._seatingCapacity} seats at Italian Bistro.`);
    return this._seatingCapacity;
  }
}
restaurant.seatingCapacity = 150;
restaurant.seatingCapacity;

or

let person = {
  _name: 'Lu Xun',
  _age: 137,

    set age(ageIn) {
    if (typeof ageIn === 'number') {
      this._age = ageIn;
    }    else {
      console.log('Invalid input');
      return 'Invalid input';
    }
  },

    get age() {
    console.log(`${this._name} is ${this._age} years old.`);
    return this._age;
  }
};

person.age = 'Thirty-nine';
person.age = 39;

console.log(person.age);


Introduction to Classes

Constructor

Although you may see similarities between class and object syntax, there is one important method that sets them apart. It's called the constructor method. JavaScript calls the constructor() method every time it creates a new instance of a class.

class Surgeon {
  constructor(name, department) {
    this.name = name;
    this.department = department;
  }
}

Instance

Now, we're ready to create class instances. An instance is an object that contains the property names and methods of a class, but with unique property values.

class Dog {
  constructor(name) {
    this.name = name;
    this.behavior = 0;
  }
}
const halley = new Dog('Halley'); // Create new Dog instance
console.log(halley.name); // Log the name value saved to halley
// Output: 'Halley'

Methods

Class method and getter syntax is the same as it is for objects except you can not include commas between methods.

class Dog {
  constructor(name) {
    this._name = name;
    this._behavior = 0;
  }

  get name() {
    return this._name;
  }

  get behavior() {
    return this._behavior;
  }

  incrementBehavior() {
    this._behavior++;
  }
}

Methods Calls

class Dog {
  constructor(name) {
    this._name = name;
    this._behavior = 0;
  }

  get name() {
    return this._name;
  }

  get behavior() {
    return this._behavior;
  }   

  incrementBehavior() {
    this._behavior++;
  }
}

let nikko = new Dog('Nikko'); // Create dog named Nikko
nikko.incrementBehavior(); // Add 1 to nikko instance's behavior

let bradford = new Dog('Bradford'); // Create dog name Bradford
console.log(nikko.behavior); // Logs 1 to the console

console.log(bradford.behavior); // Logs 0 to the console
bradford.incrementBehavior();
bradford.incrementBehavior();

console.log(nikko.behavior + ' ' + nikko.name);
console.log(bradford.behavior + ' ' + bradford.name);

or

class Surgeon {
  constructor(name, department) {
    this._name = name;
    this._department = department;
    this._remainingVacationDays = 20;
  }

  get name() {
    return this._name;
  }

  get department() {
    return this._department;
  }

  get remainingVacationDays() {
    return this._remainingVacationDays;
  }

  takeVacationDays(daysOff) {
    this._remainingVacationDays -= daysOff;
  }
}

const surgeonCurry = new Surgeon('Curry', 'Cardiovascular');
const surgeonDurant = new Surgeon('Durant', 'Orthopedics');

console.log(surgeonCurry.name);
surgeonCurry.takeVacationDays(3);
console.log(surgeonCurry.remainingVacationDays);

Inheritance

Parents and child class

class Animal {
  constructor(name) {
    this._name = name;
    this._behavior = 0;
  }

  get name() {
    return this._name;
  }

  get behavior() {
    return this._behavior;
  }

  incrementBehavior() {
    this._behavior++;
  }
}

class Cat extends Animal {
  constructor(name, usesLitter) {
    super(name);
    this._usesLitter = usesLitter;
  }
}

In the example above, we create a new class named Cat that extends the Animal class. Let's pay special attention to our new keywords: extends and super.

- The extends keyword makes the methods of the animal class available inside the cat class.
- The constructor, called when you create a new Cat object, accepts two arguments, name and usesLitter.
- The super keyword calls the constructor of the parent class. In this case, super(name) passes the name argument of the Cat class to the constructor of the Animal class. When the Animal constructor runs, it sets this._name = name; for new Cat instances.
- _usesLitter is a new property that is unique to the Cat class, so we set it in the Cat constructor.

Notice, we call super on the first line of our constructor(), then set the usesLitter property on the second line. In a constructor(), you must always call the super method before you can use the this keyword — if you do not, JavaScript will throw a reference error. To avoid reference errors, it is best practice to call super on the first line of subclass constructors.

class HospitalEmployee {
  constructor(name) {
    this._name = name;
    this._remainingVacationDays = 20;
  }

  get name() {
    return this._name;
  }

  get remainingVacationDays() {
    return this._remainingVacationDays;
  }

  takeVacationDays(daysOff) {
    this._remainingVacationDays -= daysOff;
  }
}

class Nurse extends HospitalEmployee {
  constructor(name, certifications) {
    super(name);
    this._certifications = certifications;
  }   

  get certifications() {
    return this._certifications;
  }

  addCertification(newCertification) {
    this._certifications.push(newCertification);
  }
}

const nurseOlynyk = new Nurse('Olynyk', ['Trauma','Pediatrics']);
nurseOlynyk.takeVacationDays(5);
console.log(nurseOlynyk.remainingVacationDays);
nurseOlynyk.addCertification('Genetics');
console.log(nurseOlynyk.certifications);

Static Methods

Statics methods are accessible only in the parent class. 

class HospitalEmployee {
  constructor(name) {
    this._name = name;
    this._remainingVacationDays = 20;
  }

  get name() {
    return this._name;
  }

  get remainingVacationDays() {
    return this._remainingVacationDays;
  }

  takeVacationDays(daysOff) {
    this._remainingVacationDays -= daysOff;
  }

  static generatePassword() {
    return Math.floor(Math.random() * 10000);
  }
}

class Nurse extends HospitalEmployee {
  constructor(name, certifications) {
    super(name);
    this._certifications = certifications;
  } 

    get certifications() {
    return this._certifications;
  }

  addCertification(newCertification) {
    this.certifications.push(newCertification);
  }
}

const nurseOlynyk = new Nurse('Olynyk', ['Trauma','Pediatrics']);
nurseOlynyk.takeVacationDays(5);
console.log(nurseOlynyk.remainingVacationDays);
nurseOlynyk.addCertification('Genetics');
console.log(nurseOlynyk.certifications);