const constVariableg = "string"; // can only be defined once. Global, and its value cannot be altered (unless it's an Object) let letVariable = "string"; // can only be declared once, but its value can be altered. var varVariable = "string"; // can be redefined at will.
Put default arguments and pass undefined as argument
function becomeBetter(goal, average = 50, effort = 200) {...
};
becomeBetter(100, undefined, 50);
Template literals
var backticks = `My name is ${github}`;
const developer = {
name: "Cool Guy",
age: 123,
fun: true
};
const longString = `
<div class="long">
<span>${developer.name}</span>
<p>${developer.age}</p>
</div>
`;
const people = [
{name: "Mike", age: 23},
{name: "John", age: 43}
];
const team = `
<ul>
${people.map(person => `
<li>${person.name} is ${person.age}</li>
`).join("")}
</ul>
`;
// strings == array of 'bio' substrings
// ...values == array of variables name and age
function wrapContent(strings, ...values) {
let str = '';
strings.forEach((string, i) => {
str += `${string} <strong>${(values[i] || '')}</strong>`;
});
return str
};
const name = "Johnny";
const age = 52;
const bio = wrapContent`The dude's name is ${name}; he's ${age}`;
let abc = "ABC"
// .startsWith()
abc.startsWith("A"); // true
abc.startsWith("B", 1); // true
// .endsWith()
abc.endsWith("C"); // true
// .includes()
abc.includes("AB"); // true
// .repeat()
abc.repeat(2); // "ABCABC"
const france = {
continent: "Europe",
language: "French",
sites: {
castle: "Versailles"
}
};
const { continent, language:lang } = france;
const { castle } = france.sites;
// yields `const castle`, `const continent` and `const lang`
const settings = { width: 300, color: 'black' }; // height, fontSize
const { width = 100, height = 100, color = 'blue', fontSize = 25} = settings;
const { w: width = 500, h: height = 800 } = { w: 600 };
const france = ["french", 60000000, "Europe", "Sarkozy", "Hollande", "Pompidou"]; // const france = "french,60000000,Europe"; const [language, population, continent, ...presidents] = france;
let first = "first"; let second = "second"; [first, second] = [second, first];
function convertCurrency(amount) {
const converted = {
USD: amount * 10,
GBP: amount * 5,
EUR: amount * 8
};
return converted;
};
const { USD, EUR } = convertCurrency(123);
// for OF yields the value, while IN yields the index
const devs = ["john", "joe"];
for (const dev of devs) {
console.log(dev)
}; // -> "john", "joe"
// `.entries` creates an iterable "array prototype"
for (const [index, name] of devs.entries()) {
console.log(`${name} is at index ${index}`)
};
// Read the arguments passed to the function
function unkownArgumentsAmount() {
console.log(arguments)
};
Takes something array-ish and makes it a true array You can apply a map immediately in the second argument
const ps = document.querySelectorAll("p .exemple")
const arrDivs = Array.from(ps, exemple => {
return exemple.textContent;
});
Array.of() makes an array with the arguments passed to it
.find()
const group = [{"id": "1", "name": "me"}, {"id": "2", "name": "you"}];
const person = group.find(person => person.name === "you");
// Object {id: "2", name: "you"}
.findIndex()
const personIndex = group.findIndex(person => person.name === "you");
// 1
Array.some() returns true if condition is met in array Array.every() returns true ONLY if condition is met on every item
const ages = Array.from(19, 21, 32, 25, 59); const oldEnough = ages.every(age => age >= 21); // false const leaderInGroup = ages.some(age => age >= 21); // true
const people = ["John", "Mary", "Jack"]; const twins = ["John", "Mary", "Jack"]; const everybody = [...people, ...twins]; // Duplicate an array const newEverybody = [...everybody];
const heading = document.querySelector('.jump');
heading.innerHTML = sparanWrap(heading.textContent);
function sparanWrap(word) {
return [...word].map(letter => `<span>${letter}</span>`).join('');
};
const comments = [
{id: 1, content: "Hey"},
{id: 2, content: "Bonjour"},
{id: 3, content: "Hola"},
];
const whereFrance = comments.findIndex(comment => comment.content === "Bonjour");
const noFrance = [...comments.slice(0, whereFrance), ...comments.slice(whereFrance + 1)];
console.log(noFrance)
const people = ["John", "Mary", "Jack"];
const singer = ["Sinatra", "Goodnight Irene"];
twins.push(...people);
function singer(singerName, song) {
console.log(`${singerName} sang ${song}`);
};
singer(...twins)
You can populate an object with variables without specifying their key names
const firstName = "John";
const lastName = "Doe";
const person = { firstName, lastName } // Object {firstName: "John", lastName: "Doe"}
// functions in Object
const modal = {
create(selector) {
// use this
},
create: function(selector) {
// instead of this
}
};
// create keys on the fly
const total = {
[lastName]: lastName,
[`${lastName}Classy`]: `de ${lastName}`
};
// 'zip' two arrays
const firstSinger = ["Frank", "Mark"];
const lastSinger = ["Sinatra", "Knopfler"];
const singer = {
[firstSinger.shift()]: lastSinger.shift(),
[firstSinger.shift()]: lastSinger.shift(),
}
const posts = fetch("http://some.api/url/get/items");
posts.then(data => data.json)
.then(data => { console.log(data) })
.catch((err) => { console.log(err) })
const p = new Promise((resolve, reject) => {
setTimeout(() => {
reject(Error("This error is wrapped in an error Object"));
}, 1000);
});
p.then("Hey").catch((error) => console.log(error));
const op = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("It worked");
}, 1000)
});
const posts = [
{ id: 1, author: "Hemingway" },
{ id: 2, author: "Whitman" }
];
const authors = [
{ id: 1, origin: "US", first_name: "Ernest", last_name: "Hemingway" },
{ id: 2, origin: "US", first_name: "Walt", last_name: "Whitman" }
];
function getPostById( id ) {
return new Promise( ( resolve, reject ) = & gt; {
const post = posts.find( ( post ) = & gt; post.id == id );
if ( post ) {
resolve( post );
} else {
reject( Error( "Post not found" ) );
}
} );
};
function incorporateAuthorInfo( post ) {
return new Promise( ( resolve, reject ) = & gt; {
const author = authors.find( ( author ) = & gt; author.last_name === post.author )
if ( author ) {
resolve( author );
} else {
reject( Error( "Author not found" ) );
}
} );
};
getPostById(2)
.then(post => { return incorporateAuthorInfo(post) })
.then(post => { console.log(post) })
.catch(err => { console.log(err) })
const numbers = [3, 62, 234, 7, 23, 74, 23, 76, 92];
const result = numbers.filter(number => number >= 70)
.reduce((a, b) => {
return a + b
}, 0);
// Refactor functions to arrow functions
const names = ['wes', 'kait', 'lux'];
const fullNames = names.map(function(name) {
return `${name} bos`;
});
const fullNames2 = names.map((name) => {
return `${name} bos`;
});
const fullNames3 = names.map(name => {
return `${name} bos`;
});
const fullNames4 = names.map(name => `${name} bos`);
const fullNames5 = names.map(() => `cool bos`);
const sayMyName = (name) => {
alert(`Hello ${name}!`)
}
sayMyName('Wes');