Year | Version | Support |
---|---|---|
1997 | ECMAScript 1 | All browsers |
1998 | ECMAScript 2 | All browsers |
1999 | ECMAScript 3 | All browsers |
2009 | ECMAScript 5 | All modern browsers |
2015 | ECMAScript 6 | Partial |
? | ECMAScript 7 | Poor |
Retrocompatible
A variable is a named container for a value
Three ways to declare it
But you can leave it empty right now! (except constant)
var imperator = 'Furiosa';
let auntyEntity = 'Tina Turner';
const beyondThunderdome = 3;
var master;
let blaster;
const hasToBeInitialized = true;
let text = 'mediocre';
let pi = 3.141592;
let what = null;
let none = undefined;
let yesOrNo = true;
let complex = {
key: 'value',
evenMoreObjects: {
yes: false
}
};
console.log(Math.PI) // 3.141592653589793
console.log(Date.now()) // 1525979416506
const warlords = ['Immortan Joe', 'Bullet Farmer'];
new Error('I live, I die, I live again');
A function is a fragment of code that can be invoked any time
When invoked, it can receive a list of arguments
Two different sintax, almost the same
function greet() { // ES5
console.log('hi!');
}
greet();
const sayBye = () => { // ES6
console.log('bye bye')
}
sayBye();
function ask(question) {
console.log(question + '?');
}
ask('who killed the world');
const yell = (text) => {
console.log(text + '!!')
}
yell('two enter, one leaves');
An array is a list of values, usually of the same type
Is an object with special methods, where the keys are automatically set
const originalSaga = [3, 'Mad Max', { bestOne: false }];
console.log(originalSaga[0]); // 3
console.log(originalSaga[2].bestOne); // false
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Remainder |
** | Exponential |
-- | Decrement |
++ | Increment |
function addOne(a) {
return ++a;
}
function squaredAdd(a, b) {
return (a ** 2) + (b ** 2) + (a * b);
}
function areLoselyEqual(a, b) {
return a == b;
}
function isNegativeNumber(a) {
return a < 0;
}
< | Less |
<= | Less or equal |
> | Greater |
>= | Greater or equal |
== or === | Equal |
!= or !== | Not equal |
function isTheLetterA(letter) {
return letter === 'a' || letter === 'A';
}
function isBetween(target, min, max) {
return target >= min && target <= max;
}
&& | And |
|| | Or |
! | Not |
Object values can be accessed using the dot notation or the brackets notation
const madMax4 = {
year: new Date('7/May/2015'),
title: 'Mad Max: Fury Road',
director: 'George Miller'
};
console.log(madMax4.title);
console.log(madMax4['director']);
const someProp = 'year';
console.log(madMax4[someProp]);
madMax4.stars = [
'Tom Hardy',
'Charlize Theron'
];
Array values can only be accessed with the brackets notation, using the index
We can add or modify values using the assignment operator (=)
console.log(madMax4.stars[1]);
madMax4.stars[1] = 'Charlize <3';
console.log(Object.values(madMax2));
console.log(Object.entries(madMax2));
console.log(Object.keys(madMax2));
const filmBase = {director: 'George Miller'};
const madMax2 = Object.assign(
{title: 'Road Warrior'},
filmBase
);
soundtrack.push('Buzzards Arrive');
soundtrack.pop();
const soundtrack = [
'Survive',
'Escape',
'Immortan\'s citadel',
'Blood bag'
];
soundtrack.length; // 4
soundtrack.indexOf('Escape');
soundtrack.sort();
objectsArray.sort((a, b) => {
return a.value - b.value;
});
soundtrack.concat(['Spikey Cars']);
soundtrack.join(' - ')
Conditional structures allow to execute or not a piece of code depending on a decision
The if...else structure is usefull to execute statements if a condition is true
function whoIsMadMax(film) {
if (film <= 3) {
return 'Mel Gibson';
} else {
return 'Tom Hardy';
}
}
We can use only the if part, or chain any number of else if
function getArea(poligon, side) {
if (poligon === 'square') {
return side * side;
} else if (poligon === 'triangle') {
return side * side / 2;
} else {
return new Error('Sorry')
}
}
The ternary operator is an abbreviated if else.
function whoIsMadMax(film) {
return film <= 3
? 'Mel Gibson'
: 'Tom Hardy';
}
A loop is a structure that allow us to repeat the same code a certain number of times
Loops can be placed inside other loops, which is called nested loop. Be aware, so they can increase the execution time exponentially.
A loop has (implicit or explicitly) three elements:
The for loop is the most basic form of loop in javascript
const wives = [
'Angharad',
'Toast the Knowing',
'Capable',
'The Dag',
'Cheedo the Fragile'
];
for (let i = 0; i < wives.length; i++) {
console.log(`${i}: ${wives[i]}`);
}
Counter, exit condition and iterator are easily identifiable
forEach is a shorter way to iterate over the elements of an array
const wives = [
'Angharad',
'Toast the Knowing',
'Capable',
'The Dag',
'Cheedo the Fragile'
];
wives.forEach((wife, i) => {
console.log(`${i}: ${wife});
});
for ... in is the object-equivalent of forEach
const gangs = {
theAquifer: 'Immortan Joe',
bulletFarm: 'Bullet Farmer',
gasTown: 'People Eater'
};
for (const place in gangs) {
console.log(
`${place} is lead by ${gangs[place]}`
);
}
The while statement does not need an iterator, it will run until a condition is true
let theWivesAreSave = false;
while (immortanJoe.isAlive) {
tryToKill(immortanJoe);
}
theWivesAreSave = true;
disclaimer: as a frontend dev, i'm not good at this
Functional programming (often abbreviated FP) is the process of building software by composing pure functions, avoiding shared state, mutable data, and side-effects.
Advantages
// very bad
const truck = { rider: 'Furiosa', gear: 0, started: false };
function startTruck() {
if (truck.rider !== 'Furiosa') {
return;
} else {
truck.gear = 1;
truck.started = true
}
}
startTruck();
// still bad
function startTruck(truck) {
if (truck.rider !== 'Furiosa') {
return false;
} else {
truck.gear = 1;
truck.started = true
}
}
startTruck({ rider: 'Furiosa', gear: 0, started: false });
Shared state is a variable, object, etc that exists in a shared scope.
// still bad
function startTruck(truck) {
if (truck.rider !== 'Furiosa') {
return;
} else {
truck.changeGear(1);
truck.started = true
}
}
startTruck({ rider: 'Furiosa', gear: 0, started: false });
Data shouldn't be modified after it has been created.
Be aware, that const does not mean the data is immutable
// not so bad
function startTruck(truck) {
if (truck.rider !== 'Furiosa') {
return Object.assign({}, truck, {started: false});
} else {
truck.changeGear(1);
return Object.assign({}, truck, {started: true});
}
}
startTruck({ rider: 'Furiosa', gear: 0, started: false });
A side effect is any change visible outside the called function
(apart from the returned value)
// done!
function startTruck(truck) {
return Object.assign(
{}, truck, {started: truck.rider === 'Furiosa'}
);
}
const truck = startTruck(
{ rider: 'Furiosa', gear: 0, started: false }
).changeGear(1);
Creates a new array with the results of calling a function over the elements of other array
const characters = [
'Imperator',
'Mad Max',
'Auntie',
'Toecutter'
];
const everybodyGetsACar = characters
.map(name => `${name} gets a car!`);
The function needs to return the new element
Similar to map, but reduces the array to a single value
const characters = [
'Imperator',
'Mad Max',
'Auntie',
'Toecutter'
];
const everybodyGetsACar = characters
.reduce((sentence, name) => {
return `${sentence} ${name}, `;
}, 'All of them get a car: ');
The initial value is optional
Filter returns a new array containing only some values, depending on a filtering condition
const someNumbers= [15, 8, 4, 42, 23, 16];
const smallNumbers= someNumbers
.filter(num => num <= 15);
Sometimes, a line of code will schedule something to be executed later, while the rest of the code continues running. This is called asyncronism
In javascript this is usually related to http calls or database modifications
callbacks (ES5)
promises (ES6)
async await (ES7)
asynFunction('p', result => {
console.log(result);
});
asynFunction('p').then(result => {
console.log(result);
});
async function asynFunction(p) {...}
const result = await asynFunction('p');
console.log(result);