자바스크립트 기초 강의 (ES5+) (드림코딩 by 엘리)
-
- 클래스와 오브젝트의 차이점(class vs object), 객체지향 언어 클래스 정리
- 배열 제대로 알고 쓰자. 자바스크립트 배열 개념과 APIs 총정리
- 유용한 10가지 배열 함수들. Array APIs 총정리
- JSON 개념 정리 와 활용방법 및 유용한 사이트 공유
- 비동기 처리의 시작 콜백 이해하기, 콜백 지옥 체험
- 프로미스 개념부터 활용까지 JavaScript Promise
- 비동기의 꽃 JavaScript async 와 await 그리고 유용한 Promise APIs
- 자바스크립트 최신 문법 (ES6, ES11) | 모르면 후회 하는 최신 문법과 사용법 정리
https://github.com/dream-ellie
# JavaScript reference
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference
클래스와 오브젝트의 차이점(class vs object), 객체지향 언어 클래스 정리
# JavaScript reference
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference
https://github.com/dream-ellie/learn-javascript/blob/master/notes/class.js
'use strict';
// Object-oriendted programming
// class: template
// object: instance of a class
// JavaScript classes
// - introduced in ES6
// - syntactical sugar over prototype-based inheritance
// 1. Class declarations
class Person {
// constructor
constructor(name, age) {
// fields
this.name = name;
this.age = age;
}
// methods
speak() {
console.log(`${this.name}: hello!`);
}
}
const ellie = new Person('ellie', 20);
console.log(ellie.name);
console.log(ellie.age);
ellie.speak();
// 2. Getter and setters
class User {
constructor(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
get age() {
return this._age;
}
set age(value) {
// if (value < 0) {
// throw Error('age can not be negative');
// }
this._age = value < 0 ? 0 : value;
}
}
const user1 = new User('Steve', 'Job', -1);
console.log(user1.age);
// 3. Fields (public, private)
// Too soon!
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Class_fields
class Experiment {
publicField = 2;
#privateField = 0;
}
const experiment = new Experiment();
console.log(experiment.publicField);
console.log(experiment.privateField);
// 4. Static properties and methods
// Too soon!
class Article {
static publisher = 'Dream Coding';
constructor(articleNumber) {
this.articleNumber = articleNumber;
}
static printPublisher() {
console.log(Article.publisher);
}
}
const article1 = new Article(1);
const article2 = new Article(2);
console.log(Article.publisher);
Article.printPublisher();
// 5. Inheritance
// a way for one class to extend another class.
class Shape {
constructor(width, height, color) {
this.width = width;
this.height = height;
this.color = color;
}
draw() {
console.log(`drawing ${this.color} color!`);
}
getArea() {
return this.width * this.height;
}
}
class Rectangle extends Shape {}
class Triangle extends Shape {
draw() {
super.draw();
console.log('🔺');
}
getArea() {
return (this.width * this.height) / 2;
}
toString() {
return `Triangle: color: ${this.color}`;
}
}
const rectangle = new Rectangle(20, 20, 'blue');
rectangle.draw();
console.log(rectangle.getArea());
const triangle = new Triangle(20, 20, 'red');
triangle.draw();
console.log(triangle.getArea());
// 6. Class checking: instanceOf
console.log(rectangle instanceof Rectangle);
console.log(triangle instanceof Rectangle);
console.log(triangle instanceof Triangle);
console.log(triangle instanceof Shape);
console.log(triangle instanceof Object);
console.log(triangle.toString());
let obj = { value: 5 };
function change(value) {
value.value = 7;
}
change(obj);
배열 제대로 알고 쓰자. 자바스크립트 배열 개념과 APIs 총정리
https://raw.githubusercontent.com/dream-ellie/learn-javascript/master/notes/array.js
'use strict';
// Array🎉
// 1. Declaration
const arr1 = new Array();
const arr2 = [1, 2];
// 2. Index position
const fruits = ['🍎', '🍌'];
console.log(fruits);
console.log(fruits.length);
console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[2]);
console.log(fruits[fruits.length - 1]);
console.clear();
// 3. Looping over an array
// print all fruits
// a. for
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// b. for of
for (let fruit of fruits) {
console.log(fruit);
}
// c. forEach
fruits.forEach((fruit) => console.log(fruit));
// 4. Addtion, deletion, copy
// push: add an item to the end
fruits.push('🍓', '🍑');
console.log(fruits);
// pop: remove an item from the end
const poped = fruits.pop();
fruits.pop();
console.log(fruits);
// unshift: add an item to the benigging
fruits.unshift('🍓', '🍋');
console.log(fruits);
// shift: remove an item from the benigging
fruits.shift();
fruits.shift();
console.log(fruits);
// note!! shift, unshift are slower than pop, push
// splice: remove an item by index position
fruits.push('🍓', '🍑', '🍋');
console.log(fruits);
fruits.splice(1, 1);
console.log(fruits);
fruits.splice(1, 0, '🍏', '🍉');
console.log(fruits);
// combine two arrays
const fruits2 = ['🍐', '🥥'];
const newFruits = fruits.concat(fruits2);
console.log(newFruits);
// 5. Searching
// indexOf: find the index
console.clear();
console.log(fruits);
console.log(fruits.indexOf('🍎'));
console.log(fruits.indexOf('🍉'));
console.log(fruits.indexOf('🥥'));
// includes
console.log(fruits.includes('🍉'));
console.log(fruits.includes('🥥'));
// lastIndexOf
console.clear();
fruits.push('🍎');
console.log(fruits);
console.log(fruits.indexOf('🍎'));
console.log(fruits.lastIndexOf('🥥'));
유용한 10가지 배열 함수들. Array APIs 총정리
https://github.com/dream-ellie/learn-javascript/blob/master/notes/array-api.js
// Q1. make a string out of an array
{
const fruits = ['apple', 'banana', 'orange'];
const result = fruits.join(',');
console.log(result);
}
// Q2. make an array out of a string
{
const fruits = '🍎, 🥝, 🍌, 🍒';
const result = fruits.split(',');
console.log(result);
}
// Q3. make this array look like this: [5, 4, 3, 2, 1]
{
const array = [1, 2, 3, 4, 5];
const result = array.reverse();
console.log(result);
console.log(array);
}
// Q4. make new array without the first two elements
{
const array = [1, 2, 3, 4, 5];
const result = array.slice(2, 5);
console.log(result);
console.log(array);
}
class Student {
constructor(name, age, enrolled, score) {
this.name = name;
this.age = age;
this.enrolled = enrolled;
this.score = score;
}
}
const students = [
new Student('A', 29, true, 45),
new Student('B', 28, false, 80),
new Student('C', 30, true, 90),
new Student('D', 40, false, 66),
new Student('E', 18, true, 88),
];
// Q5. find a student with the score 90
{
const result = students.find((student) => student.score === 90);
console.log(result);
}
// Q6. make an array of enrolled students
{
const result = students.filter((student) => student.enrolled);
console.log(result);
}
// Q7. make an array containing only the students' scores
// result should be: [45, 80, 90, 66, 88]
{
const result = students.map((student) => student.score);
console.log(result);
}
// Q8. check if there is a student with the score lower than 50
{
console.clear();
const result = students.some((student) => student.score < 50);
console.log(result);
const result2 = !students.every((student) => student.score >= 50);
console.log(result2);
}
console.clear();
// Q9. compute students' average score
{
const result = students.reduce((prev, curr) => prev.score + curr.score);
console.log(result / students.length);
}
// Q10. make a string containing all the scores
// result should be: '45, 80, 90, 66, 88'
{
const result = students
.map((student) => student.score)
.filter((score) => score >= 50)
.join();
console.log(result);
}
// Bonus! do Q10 sorted in ascending order
// result should be: '45, 66, 80, 88, 90'
{
const result = students
.map((student) => student.score)
.sort((a, b) => b - a)
.join();
console.log(result);
}
JSON 개념 정리 와 활용방법 및 유용한 사이트 공유
JSON에 대해 조금더 공부를 하고 싶으시면:
MDN ➡️ https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON
JavaScript.info ➡️ https://javascript.info/json
JavaScript.info 한국어 ➡️ https://ko.javascript.info/json
JSON Diff checker: http://www.jsondiff.com/
JSON Beautifier/editor: https://jsonbeautifier.org/
JSON Parser: https://jsonparser.org/
JSON Validator: https://tools.learningcontainer.com/json-validator/
https://github.com/dream-ellie/learn-javascript/blob/master/notes/json.js
'use strict';
// JSON
// JavaScript Object Notation
// 1. Object to JSON
// stringfy(obj)
let json = JSON.stringify(true);
console.log(json);
json = JSON.stringify(['apple', 'banana']);
console.log(json);
const rabbit = {
name: 'tori',
color: 'white',
size: null,
birthDate: new Date(),
jump: function () {
console.log(`${this.name} can jump!`);
},
};
json = JSON.stringify(rabbit);
console.log(json);
json = JSON.stringify(rabbit, ['name', 'color', 'size']);
console.log(json);
json = JSON.stringify(rabbit, (key, value) => {
console.log(`key: ${key}, value: ${value}`);
return key === 'name' ? 'ellie' : value;
});
console.log(json);
// 2. JSON to Object
// parse(json)
console.clear();
json = JSON.stringify(rabbit);
console.log(json);
const obj = JSON.parse(json, (key, value) => {
console.log(`key: ${key}, value: ${value}`);
return key === 'birthDate' ? new Date(value) : value;
});
console.log(obj);
rabbit.jump();
// obj.jump();
console.log(rabbit.birthDate.getDate());
console.log(obj.birthDate.getDate());
비동기 처리의 시작 콜백 이해하기, 콜백 지옥 체험
https://github.com/dream-ellie/learn-javascript/blob/master/notes/async/callback.js
'use strict';
// JavaScript is synchronous.
// Execute the code block by orger after hoisting.
// hoisting: var, function declaration
console.log('1');
setTimeout(() => console.log('2'), 1000);
console.log('3');
// Synchronous callback
function printImmediately(print) {
print();
}
printImmediately(() => console.log('hello'));
// Asynchronous callback
function printWithDelay(print, timeout) {
setTimeout(print, timeout);
}
printWithDelay(() => console.log('async callback'), 2000);
// Callback Hell example
class UserStorage {
loginUser(id, password, onSuccess, onError) {
setTimeout(() => {
if (
(id === 'ellie' && password === 'dream') ||
(id === 'coder' && password === 'academy')
) {
onSuccess(id);
} else {
onError(new Error('not found'));
}
}, 2000);
}
getRoles(user, onSuccess, onError) {
setTimeout(() => {
if (user === 'ellie') {
onSuccess({ name: 'ellie', role: 'admin' });
} else {
onError(new Error('no access'));
}
}, 1000);
}
}
const userStorage = new UserStorage();
const id = prompt('enter your id');
const password = prompt('enter your passrod');
userStorage.loginUser(
id,
password,
user => {
userStorage.getRoles(
user,
userWithRole => {
alert(
`Hello ${userWithRole.name}, you have a ${userWithRole.role} role`
);
},
error => {
console.log(error);
}
);
},
error => {
console.log(error);
}
);
프로미스 개념부터 활용까지 JavaScript Promise
https://github.com/dream-ellie/learn-javascript/blob/master/notes/async/promise.js
'use strict';
// Promise is a JavaScript object for asynchronous operation.
// State: pending -> fulfilled or rejected
// Producer vs Consumer
// 1. Producer
// when new Promise is created, the executor runs automatically.
const promise = new Promise((resolve, reject) => {
// doing some heavy work (network, read files)
console.log('doing something...');
setTimeout(() => {
resolve('ellie');
// reject(new Error('no network'));
}, 2000);
});
// 2. Consumers: then, catch, finally
promise //
.then(value => {
console.log(value);
})
.catch(error => {
console.log(error);
})
.finally(() => {
console.log('finally');
});
// 3. Promise chaining
const fetchNumber = new Promise((resolve, reject) => {
setTimeout(() => resolve(1), 1000);
});
fetchNumber
.then(num => num * 2)
.then(num => num * 3)
.then(num => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(num - 1), 1000);
});
})
.then(num => console.log(num));
// 4. Error Handling
const getHen = () =>
new Promise((resolve, reject) => {
setTimeout(() => resolve('🐓'), 1000);
});
const getEgg = hen =>
new Promise((resolve, reject) => {
setTimeout(() => reject(new Error(`error! ${hen} => 🥚`)), 1000);
});
const cook = egg =>
new Promise((resolve, reject) => {
setTimeout(() => resolve(`${egg} => 🍳`), 1000);
});
getHen() //
.then(getEgg)
.then(cook)
.then(console.log)
.catch(console.log);
비동기의 꽃 JavaScript async 와 await 그리고 유용한 Promise APIs
https://github.com/dream-ellie/learn-javascript/blob/master/notes/async/async.js
// async & await
// clear style of using promise :)
// 1. async
async function fetchUser() {
// do network reqeust in 10 secs....
return 'ellie';
}
const user = fetchUser();
user.then(console.log);
console.log(user);
// 2. await ✨
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function getApple() {
await delay(2000);
return '🍎';
}
async function getBanana() {
await delay(1000);
return '🍌';
}
async function pickFruits() {
const applePromise = getApple();
const bananaPromise = getBanana();
const apple = await applePromise;
const banana = await bananaPromise;
return `${apple} + ${banana}`;
}
pickFruits().then(console.log);
// 3. useful APIs ✨
function pickAllFruits() {
return Promise.all([getApple(), getBanana()]).then(fruits =>
fruits.join(' + ')
);
}
pickAllFruits().then(console.log);
function pickOnlyOne() {
return Promise.race([getApple(), getBanana()]);
}
pickOnlyOne().then(console.log);
https://github.com/dream-ellie/learn-javascript/blob/master/notes/async/callback-to-promise.js
// Callback Hell example
class UserStorage {
loginUser(id, password) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (
(id === 'ellie' && password === 'dream') ||
(id === 'coder' && password === 'academy')
) {
resolve(id);
} else {
reject(new Error('not found'));
}
}, 2000);
});
}
getRoles(user) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (user === 'ellie') {
resolve({ name: 'ellie', role: 'admin' });
} else {
reject(new Error('no access'));
}
}, 1000);
});
}
// Homework Answer 🚀
async getUserWithRole(user, password) {
const user = await this.loginUser(user, password);
const role = await this.getRoles(user);
return role;
}
}
// Original code from Youtube course
const userStorage = new UserStorage();
const id = prompt('enter your id');
const password = prompt('enter your passrod');
userStorage
.loginUser(id, password)
.then(userStorage.getRoles)
.then(user => alert(`Hello ${user.name}, you have a ${user.role} role`))
.catch(console.log);
// Homework Answer 🚀
userStorage
.getUserWithRole() //
.catch(console.log)
.then(console.log);
자바스크립트 최신 문법 (ES6, ES11) | 모르면 후회 하는 최신 문법과 사용법 정리
https://www.youtube.com/watch?v=36HrZHzPeuY&list=PLv2d7VI9OotTVOL4QmPfvJWPJvkmv6h-2&index=23
ES6
https://github.com/dream-ellie/learn-javascript/blob/master/notes/es6-11/es6.js
/**
* Shorthand property names
* https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Object_initializer
*
*/
{
const ellie1 = {
name: 'Ellie',
age: '18',
};
const name = 'Ellie';
const age = '18';
// 💩
const ellie2 = {
name: name,
age: age,
};
// ✨
const ellie3 = {
name,
age,
};
console.log(ellie1, ellie2, ellie3);
console.clear();
}
/**
* Destructuring Assignment
* https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
*
*/
{
// object
const student = {
name: 'Anna',
level: 1,
};
// 💩
{
const name = student.name;
const level = student.level;
console.log(name, level);
}
// ✨
{
const { name, level } = student;
console.log(name, level);
const { name: studentName, level: studentLevel } = student;
console.log(studentName, studentLevel);
}
// array
const animals = ['🐶', '😽'];
// 💩
{
const first = animals[0];
const second = animals[1];
console.log(first, second);
}
// ✨
{
const [first, second] = animals;
console.log(first, second);
}
console.clear();
}
/**
* Spread Syntax
* https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Spread_syntax
*
*/
{
const obj1 = { key: 'key1' };
const obj2 = { key: 'key2' };
const array = [obj1, obj2];
// array copy
const arrayCopy = [...array];
console.log(array, arrayCopy);
const arrayCopy2 = [...array, { key: 'key3' }];
obj1.key = 'newKey';
console.log(array, arrayCopy, arrayCopy2);
// object copy
const obj3 = { ...obj1 };
console.log(obj3);
// array concatenation
const fruits1 = ['🍑', '🍓'];
const fruits2 = ['🍌', '🥝'];
const fruits = [...fruits1, ...fruits2];
console.log(fruits);
// object merge
const dog1 = { dog: '🐕' };
const dog2 = { dog: '🐶' };
const dog = { ...dog1, ...dog2 };
console.log(dog);
console.clear();
}
/**
* Default parameters
* https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/Default_parameters
*/
{
// 💩
{
function printMessage(message) {
if (message == null) {
message = 'default message';
}
console.log(message);
}
printMessage('hello');
printMessage();
}
// ✨
{
function printMessage(message = 'default message') {
console.log(message);
}
printMessage('hello');
printMessage();
}
console.clear();
}
/**
* Ternary Operator
* https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
*/
{
const isCat = true;
// 💩
{
let component;
if (isCat) {
component = '😸';
} else {
component = '🐶';
}
console.log(component);
}
// ✨
{
const component = isCat ? '😸' : '🐶';
console.log(component);
console.log(isCat ? '😸' : '🐶');
}
console.clear();
}
/**
* Template Literals
* https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Template_literals
*/
{
const weather = '🌤';
const temparature = '16°C';
// 💩
console.log(
'Today weather is ' + weather + ' and temparature is ' + temparature + '.'
);
// ✨
console.log(`Today weather is ${weather} and temparature is ${temparature}.`);
}
ES11
https://github.com/dream-ellie/learn-javascript/blob/master/notes/es6-11/es11.js
/**
* 관련 강의 영상: https://youtu.be/36HrZHzPeuY
*/
/**
* Optional Chaining (ES11)
* https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Optional_chaining
*/
{
const person1 = {
name: 'Ellie',
job: {
title: 'S/W Engineer',
manager: {
name: 'Bob',
},
},
};
const person2 = {
name: 'Bob',
};
// 💩💩💩💩💩💩
{
function printManager(person) {
console.log(person.job.manager.name);
}
printManager(person1);
// printManager(person2);
}
// 💩💩💩
{
function printManager(person) {
console.log(
person.job
? person.job.manager
? person.job.manager.name
: undefined
: undefined
);
}
printManager(person1);
printManager(person2);
}
// 💩
{
function printManager(person) {
console.log(person.job && person.job.manager && person.job.manager.name);
}
printManager(person1);
printManager(person2);
}
// ✨
{
function printManager(person) {
console.log(person.job?.manager?.name);
}
printManager(person1);
printManager(person2);
}
console.clear();
}
/**
* Nullish Coalescing Operator (ES11)
* https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
*/
{
// Logical OR operator
// false: false, '', 0, null, undefined
{
const name = 'Ellie';
const userName = name || 'Guest';
console.log(userName);
}
{
const name = null;
const userName = name || 'Guest';
console.log(userName);
}
// 💩
{
const name = '';
const userName = name || 'Guest';
console.log(userName);
const num = 0;
const message = num || 'undefined';
console.log(message);
}
// ✨
{
const name = '';
const userName = name ?? 'Guest';
console.log(userName);
const num = 0;
const message = num ?? 'undefined';
console.log(message);
}
}