const foo = true; // typeof foo => "boolean"
const bar = false; // typeof bar => "boolean"
let foo; // typeof foo => "undefined"
const bar = null; // typeof bar => "object" (legacy reasons)
let foo; // typeof foo => "undefined"
bar; // (window.bar) typeof bar => "undefined"
const baz = {};
baz.buzz; // undefined
const one = 1; // typeof one => "number"
const total = 10.1234; // typeof total => "number"
const hex = 0xFF; // (255) typeof hex => "number"
Number('1'); // 1
Number(false); // 0
Number(true); // 1
Number('hello'); // NaN
typeof NaN; // ?
Number('1'); // 1
Number(false); // 0
Number(true); // 1
Number('hello'); // NaN
typeof NaN; // "number"
const hello = 'Hello, World!';
const name = 'John';
const helloJ1 = 'Hello, ' + name + '!';
const helloJ2 = `Hello, ${name}!`; // template literal
// helloJ1, helloJ2 => "Hello, John!"
x = y
x += y π x = x + y
x -= y π x = x - y
x *= y π x = x * y
x /= y π x = x / y
==
!=
===
!==
>
>=
<
<=
&&
||
!
condition ? val1 : val2
var hello = 'Hello, World!';
var FORTY2 = 42;
var _done = true;
var $$$ = 'money money';
var 2fast2furious = 'Vin Diesel';
var if = 'Nope, not working!';
var discount% = '10%';
var name = 'John Doe';
window.name // "John Doe"
function greetings() {
var fullName = 'John Doe'; // Local scope
return `Hello, ${fullName}`;
}
greetings();
fullName // Error: fullName is not defined
window.fullName // undefined
var a = 1;
var b = 2;
if (a === 1) {
var a = 11; // Global scope
let b = 22; // Block scope (if)
}
a // ?
b // ?
var a = 1;
var b = 2;
if (a === 1) {
var a = 11; // Global scope
let b = 22; // Block scope (if)
}
a // 11
b // 2
const foo; // Error: missing initializer
const bar = 'bar';
bar = 'buzz'; // Error: Assignment to constant
const names = [ 'Alice', 'Bob' ];
names.push('John');
names // [ "Alice", "Bob", "John" ]
function sayHi() {
console.log('Hi!');
}
sayHi(); // "Hi!", returns undefined
function add(a, b) {
return a + b;
}
add(1, 2); // 3
add(1, 2); // 3
function add(a, b) {
return a + b;
}
const sayHi = function() { // Anonymous function
console.log('Hi!');
}
sayHi(); // "Hi!"
const add = function addNumbers(a, b) {
return a + b;
}
add(1, 2); // 3
add.name; // "addNumbers"
const add = (a, b) => {
const sum = a + b;
return sum;
}
add(1, 2); // 3
const increment = a => {
const b = a++;
return b;
}
increment(1); // 2
const add = (a, b) => a + b;
add(1, 2); // 3
add(1, 2); // TypeError: add is not a function
var add = (a, b) => a + b;
function User(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
const john = new User('John', 'Doe');
john.firstName; // "John"
john.lastName; // "Doe"
function add(a) {
return function(b) {
return a + b;
}
}
const add10 = add(10); // add10 is a closure
add10(1); // 11
add10(2); // 12
if (a > 10) {
// do something
} else if (a > 5) {
// do something else
} else {
// do something else, again
}
switch (color) {
case 'RED':
// do something when color === 'RED'
break;
case 'BLUE':
// do something when color === 'BLUE'
break;
default:
// do something when color is not 'RED' or 'BLUE'
}
switch (x) {
case 1:
console.log(1);
break;
case 2:
console.log(2);
default:
console.log(-1);
}
const names = [ 'Alice', 'Bob', 'John' ];
for (let i = 0; i < names.length; i++) {
console.log(names[i]);
}
>> Alice
>> Bob
>> John
const names = [ 'Alice', 'Bob', 'John' ];
for (let name of names) {
console.log(name);
}
>> Alice
>> Bob
>> John
let n = 0;
let x = 0;
while (n < 3) {
n++;
x += n;
}
// x = ?
let n = 0;
let x = 0;
while (n < 3) {
n++;
x += n;
}
// x = 6
const book = {}; // Empty object
const book = { // Or with properties
title: 'A Game of Thrones',
published: new Date('August 1, 1996'),
author: {
name: 'George R. R. Martin'
}
};
book.title = 'A Clash of Kings';
// or
book['title'] = 'A Clash of Kings'
// Nested property
book.author.birth = new Date('September 20, 1948');
const bookTitle = book.title;
// or book['title']
const authorName = book.author.name;
// or book['author']['name']
console.log(bookTitle); // A Clash of Kings
console.log(authorName); // George R. R. Martin
const { title } = book;
const { name } = book.author;
console.log(title); // ?
console.log(name); // ?
const { title } = book;
const { name } = book.author;
console.log(title); // A Clash of Kings
console.log(name); // George R. R. Martin
// Empty array creation
const emptyArray = [];
// Array creation with elements
const names = [ 'Alice', 'Bob', 'John' ];
console.log(names.length); // 3
const names = [ 'Alice', 'Bob', 'John' ];
names[0]; // "Alice"
names[1]; // "Bob"
// Get last element
names[names.length - 1]; // "John"
const names = [ 'Alice', 'Bob', 'John' ];
const [alice] = names;
console.log(alice); // Alice
const [, , john] = names;
console.log(john); // John
const items = [ 'Alice', 'Bob', 'John' ];
items[2] = 'Jane';
items.push(100);
console.log(items); // ?
const items = [ 'Alice', 'Bob', 'John' ];
items[2] = 'Jane';
items.push(100);
console.log(items); // ["Alice", "Bob", "Jane", 100]
const names = [ 'Alice', 'Bob', 'John' ];
names.forEach(name => {
console.log(name);
});
>> Alice
>> Bob
>> John
const names = [ 'Alice', 'Bob', 'John' ];
const fnames = names
.filter(name => name.length > 3);
console.log(fnames); // ["Alice", "John"]
const names = [ 'Alice', 'Bob', 'John' ];
const newNames = names
.map(name => name.substring(0, 2));
console.log(newNames); // ["Al", "Bo", "Jo"]
const numbers = [ 1, 2, 3 ];
const sum = numbers
.reduce((total, number) => total += number);
console.log(sum); // 6
const foo = '1';
const bar = 1;
foo == bar // true, coercion!
foo === bar // false
const ten = 10;
const thousand = '1000';
ten + thousand // ?
const ten = 10;
const thousand = '1000';
ten + thousand // "101000"
const names1 = [ 'Alice', 'Bob' ];
const names2 = [ 'John', 'Jane' ];
names1 + names2 // ?
const names1 = [ 'Alice', 'Bob' ];
const names2 = [ 'John', 'Jane' ];
names1 + names2 // "Alice,BobJohn,Jane"
const hundred = '100';
const truthy = true;
hundred + truthy // ?
const hundred = '100';
const truthy = true;
hundred + truthy // "100true"
const five = 5;
const four = '4';
five - four // ?
const five = 5;
const four = '4';
five - four // 1
const five = 5;
const four = [ 4 ];
five - four // ?
const five = 5;
const four = [ 4 ];
five - four // 1
const five = 5;
const numbers = [ '1', '2', '3' ];
five - numbers // ?
const five = 5;
const numbers = [ '1', '2', '3' ];
five - numbers // NaN
const five = 5;
const falsy = false;
five - falsy // ?
const five = 5;
const falsy = false;
five - falsy // 5
const foo = 'foo';
const ten = 10;
foo || ten // ?
const foo = 'foo';
const ten = 10;
foo || ten // "foo"
function hello(name) {
return `Hello, ${name || 'Anonymous'}`;
}
hello('John'); // "Hello, John"
hello(); // "Hello, Anonymous"
const foo = 'foo';
const ten = 10;
foo && ten // ?
const foo = 'foo';
const ten = 10;
foo && ten // 10
if (false)
if (null)
if (undefined)
if (0)
if (NaN)
if ('')
if ("")
if (document.all) // Legacy, browser detection
console.log(this); // Window { ... }
var one = 1;
console.log(window.one); // 1
console.log(this.one); // 1
this.two = 2;
console.log(two); // 2
console.log(window.two); // 2
function add(a, b) {
return a + b + this.c;
}
var c = 3;
add(1, 2); // 6
function add(a, b) {
return a + b + this.c;
}
var c = 3;
const obj = { c: 4 };
add.call(obj, 1, 2); // ?
// or add.apply(obj, [1, 2]);
function add(a, b) {
return a + b + this.c;
}
var c = 3;
const obj = { c: 4 };
add.call(obj, 1, 2); // 7
// or add.apply(obj, [1, 2]);
var a = 1;
const obj = {
a: 2,
add: function(b, c) {
return this.a + b + c;
}
}
obj.add(2, 3); // ?
var a = 1;
const obj = {
a: 2,
add: function(b, c) {
return this.a + b + c;
}
}
obj.add(2, 3); // 7
function User(name) {
this.name = name;
}
const john = new User('John Doe');
console.log(john.name); // John Doe
var a = 1;
const obj = {
a: 2,
add: (b, c) => {
return this.a + b + c;
}
};
obj.add(2, 3); // ?
var a = 1;
const obj = {
a: 2,
add: (b, c) => {
return this.a + b + c;
}
};
obj.add(2, 3); // 6
// Custom function
function Person(name) { this.name = name; }
Person.prototype // {}
// Built-in function
Array.prototype // { ..., pop: f, push: f, ... }
Person.prototype.who = function() {
return `I'm ${this.name}`;
}
const john = new Person('John');
const alice = new Person('Alice');
alice.who = function() {
return `This is ${this.name}`;
}
john.who() // "I'm John"
alice.who() // "This is Alice"
Β
class Person {
constructor(name) {
this.name = name;
}
who() {
return `Hi, I'm ${this.name}`;
}
}
const john = new Person('John');
john.who(); // "Hi, I'm John"
console.log(john); // { name: "John" }
console.log(Person.prototype); // { who: f }
class Developer extends Person {
constructor(name, language) {
super(name);
this.language = language;
}
}
const jane = new Developer('Jane', 'JavaScript');
jane.who(); // "Hi, I'm Jane"
console.log(jane.language); // JavaScript
// file foo.js
export default class {
constructor() { ... }
}
// file bar.js
export default function() { ... }
// file baz.js
export default { ... }
// file dev.js
export class Developer { ... }
export function hire(developer) { ... }
export const FMKS = [ 'React', 'Vue', 'Angular' ];
import Foo from './foo.js';
import bar from './bar.js';
import baz from './baz.js';
import { Developer, hire, FMKS } from './dev.js';
import * as dev from './dev.js';
const alice = dev.Developer('Alice', 'JavaScript');
dev.hire(alice);
alice.chooseFramework(dev.FMKS);
<h1 class="title hello">Hello, World!</h1>
h1.getAttribute('class'); // "title hello"
h1.className; // "title hello"
h1.classList; // [ "title", "hello" ]
const h1 = document.createElement('h1');
h1.textContent = 'Hello, World!';
document.body.appendChild(h1);
<body></body>
<body>
<h1>Hello, World!</h1>
</body>
// Get element by type
const h1 = document.querySelector('h1');
<body>
<h1>Hello, World!</h1>
</body>
// Get element by id
const h1 = document.querySelector('#title');
<body>
<h1 id="title">Hello, World!</h1>
</body>
// Get element(s) by class
const lis = document.querySelectorAll('.name');
<ul>
<li class="name">John</li>
<li class="name">Jane</li>
<li class="name">Alice</li>
</ul>
// Get element by attribute
const input = document
.querySelector('[name="search"]');
<input name="search">
const h1 = document.querySelector('#title');
const div = h1.parentElement;
<body>
<div class="greetings">
<h1 id="title">Hello, World!</h1>
</div>
</body>
const div = document.querySelector('.greetings');
const h1 = div.firstElementChild;
<div class="greetings">
<h1>Hello, World!</h1>
<h2>My name is John</h2>
</div>
const div = document.querySelector('.greetings');
const h2 = div.lastElementChild;
<div class="greetings">
<h1>Hello, World!</h1>
<h2>My name is John</h2>
</div>
const h1 = document.querySelector('h1');
const h2 = h1.nextElementSibling;
<div class="greetings">
<h1>Hello, World!</h1>
<h2>My name is John</h2>
</div>
const h2 = document.querySelector('h2');
const h1 = h2.previousElementSibling;
<div class="greetings">
<h1>Hello, World!</h1>
<h2>My name is John</h2>
</div>
const h1 = document.querySelector('h1');
h1.remove();
<body>
<h1>Hello, World!</h1>
</body>
<body></body>
window.addEventListener('click', $event => {
console.log($event.clientX, $event.clientY);
});
// or
window.onclick = $event => {
console.log($event.clientX, $event.clientY);
};
const logEventPosition = $event => {
console.log($event.clientX, $event.clientY);
}
// function logEventPosition($event) { ... }
window.addEventListener('click', logEventPosition);
// or
window.onclick = logEventPosition;
$.ajax('http://localhost:8080/tv-shows')
.done(tvShows => { // callback
console.log(`success, tvShows = ${tvShows}`);
})
.fail(() => { // callback
console.log('error');
})
.always(() => { // callback
console.log('complete');
});
setTimeout(() => {
console.log(`I'm 1 second late`);
}, 1000);
// or
const message = () => { // function message() { ... }
console.log(`I'm 1 second late`);
};
setTimeout(message, 1000);
setTimeout(() => {
setTimeout(() => {
setTimeout(() => {
setTimeout(() => {
console.log(`I'm 4 seconds late!`);
}, 1000);
}, 1000);
}, 1000);
}, 1000);
function timeout1() { setTimeout(timeout2, 1000); }
function timeout2() { setTimeout(timeout3, 1000); }
function timeout3() { setTimeout(timeout4, 1000); }
function timeout4() {
setTimeout(() => {
console.log(`I'm 4 seconds late!`);
}, 1000);
}
timeout1();
fetch('/api/names').then(response => {
// Promise was resolved
if (response.status === 200) {
...
}
}, error => {
// Promise was rejected
console.error(error);
});
fetch('/api/names')
.then(response => {
throw new Error('Ugh!');
})
.catch(error => {
// Promise was rejected
console.error(error);
});
function toUpperCase(names) { ... }
fetch('/api/names')
.then(response => response.json())
.then(data => {
const { names } = data; // [ "John", "Jane" ]
return toUpperCase(names);
})
.then(names => {
console.log(names); // [ "JOHN", "JANE" ]
});
function getBurgers() {
return new Promise(resolve => {
setTimeout(() => {
resolve('πππ');
}, 1000);
});
}
getBurgers().then(burgers => {
// After 1 second
console.log(burgers); // πππ
});
function getBurgers() {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject('πππ');
}, 1000);
});
}
getBurgers().then(() => {}, eggplants => {
// After 1 second
console.log(eggplants); // πππ
});
const promise1 = Promise.resolve(1);
const promise2 = Promise.resolve(2);
const promise3 = Promise.resolve(3);
Promise
.all([promise1, promise2, promise3])
.then(responses => {
console.log(responses); // [1, 2, 3]
});
function getBurgers() { return new Promise(...); }
function getBeers() { return new Promise(...); }
async function menu() {
const burgers = await getBurgers();
const beers = await getBeers();
console.log(burgers, beers); // πππ, πΊπΊπΊ
}
menu();
function getBurgers() { return new Promise(...); }
async function menu() {
try {
const burgers = await getBurgers();
} catch (eggplants) {
console.log(eggplants); // πππ
}
}
menu();