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

Introduced in ES6, they simplify the way functions are written

if {} else {}

const 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)
}
Made with Slides.com