728x90

1. 동기(synchronous)와 비동기(asynchronous)

동기란, 호이스팅(선언이 제일 위로 올라가는 것)이 된 이후부터 코드가 작성된 순서대로 작동한다는 의미이다. 

동기란 말을 처음 들었을 때는 동기화란 단어가 생각이 나서 "어떤 작업이 동시에 같이 일어나는 것인가?"라 생각을 했었는데, 전혀 다르다.

반면 비동기는 JavaScript의 동기적인 특성인 코드가 작성된 순서를 따르지 않고, 특정 요청에 의해 해당 코드에 지연이 발생하더라도 기다리지 않고 바로 이어서 다음 코드를 실행한다는 의미이다. 

// Synchronous
function first() {
  console.log("first"); // 첫번째로 실행되고,
}
function second() {
  console.log("second"); // 이어서 바로 실행된다. 
}
first()
second()
	
// Asynchronous
function first() {
  setTimeout(() => console.log(first), 5000); 
  // first 함수가 호출되고, 5초 동안 기다린 다음 결과값을 출력하고, 그 다음으로 second 함수가 실행되는게 아니다.
}
function second() {
  console.log("second"); 
  // first 함수가 호출되고, 5초의 시간이 흐르는 사이에 second 함수를 실행하고, 이후에 first 함수의 결과값이 출력된다.
}
first()
second()

 

2. callback(콜백)

callback 함수는 다른 함수가 실행을 끝낸 뒤 실행되는 즉, call back 되는 함수를 말한다.

함수의 parameter(매개변수)로 들어가서 실행되는 함수이다.

// Synchronous callback
function synchronousPrint(print) {
  print();
}
synchronousPrint(() => console.log("hello")); 
// hello를 출력하는 함수를 인자(argument)로 synchronous 함수에 전달 ==> 곧바로 synchronous 함수 실행(동기)

// Asynchronous callback
function asynchronousPrint(print, timeout) {
  setTimeout(print, timeout);
}
asynchronosPrint(() => console.log("hello"), 2000); 
// hello를 출력하는 함수를 인자(argument)로 asynchronous 함수에 전달 ==> 2초 후 asynchronous 함수 실행(비동기)

callback hell(콜백지옥)의 문제점 

1. 가독성이 떨어진다. => 어디서 어떻게 연결되어지는지 한눈에 알아보기 힘들다. 

2. 디버깅, 에러 분석, 유지/보수가 어렵다. 1번 이유때문.

 

3. Promise

Promise란?

JavaScript에서 제공하는 비동기를 간편하게 처리할 수 있도록 도와주는 object(객체)

네트워크 통신을 하거나, 파일을 읽어오는 행위 등 시간이 걸리는 일들은 promise를 만들어서 비동기적(병렬로 처리한다고 이해하면 쉬울 것 같다.)으로 처리하는 것이 좋다. 

Promise의 state는 뭘까?

promise의 state란 promise의 처리 과정을 의미한다.

기능이 수행 중인지(pending), 완료가 되어서 성공했는지(fulfilled), 실패했는지(rejected)를 나타내는 상태

Producer, Consumers란?

// 1. Producer(원하는 기능을 수행해서 해당하는 데이터를 만들어낸다.)
// Promise가 생성되면 자동적으로 실행된다.
const promise = new Promise((resolve, reject) => {
  console.log("doing somthing...");
  setTimeout(() => {
    resolve("Hello, World!"); // 콜백 함수의 인자 resolve를 호출하면 이행(fulfilled) 상태가 된다.
    // reject(new Error("no network")); // reject를 호출하면 실패(rejected) 상태가 된다. 
  }, 2000);
});

// 2. Consumers(원하는 데이터를 소비한다): then, catch, finally
promise
  .then((value) => {
    console.log(value);
  }) // 이행(fulfilled) 상태가 되면 then()을 이용하여 처리 결과 값을 받는다. 
  .catch((error) => {
    console.log(error);
  }) // 실패(rejected) 상태가 되면 catch()를 이용하여 처리 결과 값을 받는다. 
  .finally(() => {
    console.log("Done");
  }); // promise 이행/실패에 상관없이 마지막에 호출되어진다.

Promise chaining이란?

여러 개의 promise를 연결하는 것.

const fetchNumber = new Promise((resolve, reject) => {
  setTimeout(() => resolve(1), 1000);
}); // 이행 상태가 되어 1초뒤 resolve에 값이 들어온다. 

fetchNumber
  .then((num) => num * 2) // num parameter(매개변수)에 1이 들어오고 해당 콜백함수를 수행한 결과 값 2를 리턴한다.
  .then((num) => num * 3) // num parameter(매개변수)에 2가 들어오고 해당 콜백함수를 수행한 결과 값 6을 리턴한다.
  .then((num) => {
    return new Promise((resolve, reject) => {
      setTimeout(() => resolve(num - 1), 1000);
    });
  }) // 새로운 promise를 만들어 1초 뒤 resolve에 5가 들어온다. 
  .then((num) => console.log(num)); // num parameter(매개변수)에 5가 들어오고 해당 콜백함수를 수행한다.

 

4. async/await

async와 await 이란? 

깔끔하게 promise를 사용할 수 있는 방법

Syntactic sugar

기능은 동일하지만 더 간결한 코드를 사용함으로써 직관성/편의성을 높여주는 프로그래밍 문법

ex) 삼항 연산자(Conditional (ternary) operator), 애로우 함수(arrow function), async 등등

async 사용 방법

// 기존 promise 사용 방법
function fetchUser() {
  return new Promise((resolve, reject) => {
    // do network request in 10 secs...
    resolve("ellie");
  });
}

// async 사용 방법(async = Syntactic sugar), 함수 앞에 async라는 키워드만 넣어주면 끝.
async function fetchUser() {
  // do network request in 10 secs...
  return "ellie";
}

const user = fetchUser();
user.then(console.log);
console.log(user);

await 사용 방법

// delay를 주는 promise 생성
function delay(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

// 1초뒤 🍎를 받아오는 promise를 async 기능을 사용해서 생성
async function getApple() { // await 키워드는 async가 붙은 함수 안에서만 사용 가능
  await delay(1000);
  return "🍎";
}

// 1초뒤 🍌를 받아오는 promise를 async 기능을 사용해서 생성
async function getBanana() { 
  await delay(1000);
  return "🍌";
}

// 기존 promise를 사용해서 결과 값을 받아오는 방법(callback 지옥과 다를바 없다.)
function pickFruits() {
  return getApple().then((apple) => {
    return getBanana().then((banana) => `${apple} + ${banana}`);
  });
}

// await를 사용해서 결과 값을 받아오는 방법
async function pickFruits() {
  // JavaScript 특성상 동기적으로 🍎, 🍌의 promise를 실행할텐데,(2초가 걸리겠지)
  // 둘 사이의 연관성이 없다면 굳이 동기적으로 받아올 필요가 없다.
  // 따라서 Promise가 생성되면 자동적으로 실행되는 특징을 이용해서 변수(아래 두줄)를 생성해준다.
  // 두 함수가 동시에 실행되므로 시간 단축!(1초!)
  const applePromise = getApple();
  const bananaPromise = getBanana();
  const apple = await applePromise;
  const banana = await bananaPromise;
  return `${apple} + ${banana}`;
}

// 유용한 promise API: Promise.all(모든 promise들이 병렬적으로 작동해서 배열에 전달된다.)
function pickAllFruits() {
  return Promise.all([getApple(), getBanana()]) //
    .then((fruits) => fruits.join(" + "));
}

// 유용한 promise API: Promise.race(배열에 가장 먼저 전달된 promise 값을 받아온다.)
function pickOnlyOne() {
  return Promise.race([getApple(), getBanana()]);
}

 

참고 자료

드림 코딩 유튜브 - 자바스크립트 11~13

Evans Library

[번역] JavaScript: 도대체 콜백이 뭔데?

 

반응형
728x90

13. 비동기의 꽃 JavaScript async 와 await 그리고 유용한 Promise APIs | 프론트엔드 개발자 입문편 (JavaScript ES6)

// async & await
// clear style of using promise :)

// 1. async
// function fetchUser() {
//   return new Promise((resolve, reject) => {
//     // do network request in 10 secs...
//     resolve("ellie");
//   });
// }

async function fetchUser() {
  // do network request 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 "🍌";
}

// function pickFruits() {
//   return getApple().then((apple) => {
//     return getBanana().then((banana) => `${apple} + ${banana}`);
//   });
// }

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 Promise 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);
반응형
728x90

11. 비동기 처리의 시작 콜백 이해하기, 콜백 지옥 체험 😱 JavaScript Callback | 프론트엔드 개발자 입문편 (JavaScript ES6)

"use strict";

// JavaScript is synchronous.
// Execute the code block in order after hoisting.
// hoisting: var, function declaration // 변수나 함수를 제일 위로 끌어올려 주는 것
console.log("1"); // 동기
// setTimeout(function () {
//   console.log("2");
// }, 1000);
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 password");
userStorage.loginUser(
  id,
  password,
  (user) => {
    userStorage.getRoles(
      user,
      (userWithRoles) => {
        alert(
          `Hello ${userWithRoles.name}, you have a ${userWithRoles.role} role`
        );
      },
      (error) => {
        console.log(error);
      }
    );
  },
  (error) => console.log(error)
);
반응형
728x90

10. JSON 개념 정리 와 활용방법 및 유용한 사이트 공유 JavaScript JSON | 프론트엔드 개발자 입문편 (JavaScript ES6)

// 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(),
  //   symbol: Symbol("id"), // Symbol은 JSON에 포함되지 않는다.
  jump: () => {
    console.log(`${this.name} can jump!`);
  },
};

json = JSON.stringify(rabbit);
console.log(json);

json = JSON.stringify(rabbit, ["name", "color", "size"]);
console.log(json);

console.clear();
json = JSON.stringify(rabbit, (key, value) => {
  console.log(`key: ${key}, value: ${value}`);
  //   return value;
  return key === "name" ? "ellie" : value;
});
console.log(json);

// 2. JSON to Object
// parse(json)
console.clear();
json = JSON.stringify(rabbit);
const obj = JSON.parse(json, (key, value) => {
  console.log(`key: ${key}, value: ${value}`);
  //   return value;
  return key === "birthDate" ? new Date(value) : value; // string을 다시 object로..
});
console.log(obj);
rabbit.jump();
// obj.jump(); // JSON으로 변환될때 함수는 포함되지 않는다.

console.log(rabbit.birthDate.getDate());
console.log(obj.birthDate.getDate()); // JSON으로 넘어가면서 string이 되었기 때문에, parse를 이용해 다시 object로 넘어와도 여전히 string이다.
반응형
728x90

9. 유용한 10가지 배열 함수들. Array APIs 총정리 | 프론트엔드 개발자 입문편 ( JavaScript ES6)

// Q1. make a string out of an array
{
  const fruits = ["apple", "banana", "orange"];
  // di it yourself!
  // console.log(fruits.toString()); // .join과 .toString의 차이는 구분자(seperator)
  // answer
  const result = fruits.join(" and ");
  console.log(result);
}

// Q2. make an array out of a string
{
  const fruits = "🍎, 🥝, 🍌, 🍒";
  // do it yourself!
  // const fruit = fruits.split(",");
  // console.log(fruit);
  // answer
  const fruit = fruits.split(",");
  console.log(fruit);
}

// Q3. make this array look like this: [5, 4, 3, 2, 1]
{
  const array = [1, 2, 3, 4, 5];
  // do it yourself!
  // const reverseArray = array.reverse();
  // console.log(reverseArray);
  // answer
  const reverseArray = array.reverse();
  console.log(reverseArray);
  console.log(array); // 원래 배열도 바뀐다.
}

// Q4. make new array without the first two elements
{
  const array = [1, 2, 3, 4, 5];
  // do it yourself!
  // const result = array.slice(2);
  // const resultNew = array.slice(2, 5);
  // console.log(result);
  // console.log(resultNew);
  // // answer
  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
{
  // do it yourself!
  // for (let i = 0; i < students.length; i++) {
  //   if (students[i].score === 90) {
  //     console.log(students[i]);
  //   }
  // }
  // answer
  // const result = students.find(function (value) {
  //   return value.score === 90;
  // });
  const result = students.find((value) => value.score === 90);
  console.log(result);
}

// Q6. make an array of enrolled students
{
  // do it yourself!
  // const result = students.filter((value) => value.enrolled === true);
  // console.log(result);
  // // answer
  const result = students.filter((student) => student.enrolled === true);
  console.log(result);
}

// Q7. make an array containing only the students' scores
// result should be: [45, 80, 90, 66, 88]
{
  // do it yourself!
  // let result = [];
  // for (let i = 0; i < students.length; i++) {
  //   result.push(students[i].score);
  // }
  // console.log(result);
  // answer
  const result = students.map((student) => student.score);
  console.log(result);
}

// Q8. check if there is a student with the score lower than 50
{
  // do it yourself!
  // const result = students.some((student) => student.score < 50);
  // console.log(result);
  // answer
  const result = students.some((student) => student.score < 50);
  console.log(result);

  const result2 = !students.every((student) => student.score >= 50);
  console.log(result2);
}

// Q9. compute students' average score
{
  //do it yourself!
  // let result = 0;
  // for (let i = 0; i < students.length; i++) {
  //   result += students[i].score;
  // }
  // console.log(result / 5);
  // answer
  // const result = students.reduce((prev, curr) => {
  //   console.log("----------");
  //   console.log(prev);
  //   console.log(curr);
  //   return prev + curr.score;
  // }, 0);
  const result = students.reduce((prev, curr) => prev + curr.score, 0);
  console.log(result / students.length);
}

// Q10. make a string containing all the scores
// result should be: '45, 80, 90, 66, 88'
{
  // do it yourself!
  // const result = students.map((student) => student.score);
  // const resultArray = result.join();
  // console.log(resultArray);
  // answer
  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'
{
  // do it yourself!
  // const result = students
  //   .map((student) => student.score)
  //   .sort((a, b) => a - b)
  //   .join();
  // console.log(result);
  // answer
  const result = students
    .map((student) => student.score)
    .sort((a, b) => a - b)
    .join();
  console.log(result);
}
반응형
728x90

8. 배열 제대로 알고 쓰자. 자바스크립트 배열 개념과 APIs 총정리 | 프론트엔드 개발자 입문편 (JavaScript ES6 )

"use strict";

// Array

// 1. Declaration
const arr1 = new Array();
const arr2 = [];

// 2. Index position
const fruits = ["apple", "banana"];
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. for each
// fruits.forEach(function (fruit, index) {
//   console.log(fruit, index);
// });

// fruits.forEach((fruit, index) => {
//   console.log(fruit, index);
// });

// fruits.forEach((fruit, index) => console.log(fruit, index));
fruits.forEach((fruit) => console.log(fruit));

// 4. Addtion, deletion, copy
// push: add an item to the end
fruits.push("strawberry", "peach");
console.log(fruits);

// pop: remove an item from the end
fruits.pop();
fruits.pop();
console.log(fruits);

// unshift: add an item to the beginning
fruits.unshift("strawberry", "peach");
console.log(fruits);

// shift: remove an item from the beginning
fruits.shift();
fruits.shift();
console.log(fruits);

// note!! shift, unshift are slower than pop, push: 나머지 전체가 움직여야 하기 때문에
// splice: remove an item by index position
fruits.push("strawberry", "peach", "lemon");
console.log(fruits);
fruits.splice(1, 1);
console.log(fruits);
fruits.splice(1, 1, "greenapple", "watermelon");
// fruits.splice(1, 0, "greenapple", "watermelon");
console.log(fruits);

// combine two arrays
const fruits2 = ["coconut", "durian"];
const newFruits = fruits.concat(fruits2);
console.log(newFruits);

// 5. Searching
// indexOf: find the index
console.clear();
console.log(fruits);
console.log(fruits.indexOf("apple"));
console.log(fruits.indexOf("lemon"));
console.log(fruits.indexOf("durian")); // 찾는 값이 없을 경우 -1을 출력

// includes
console.log(fruits.includes("durian"));
console.log(fruits.includes("peach"));

// lastIndexOf
console.clear();
fruits.push("apple");
console.log(fruits);
console.log(fruits.indexOf("apple")); // 첫번째 값의 index만 출력
console.log(fruits.lastIndexOf("apple")); // 마지막 값의 index만 출력
반응형
728x90

7. 오브젝트 넌 뭐니? | 프론트엔드 개발자 입문편 (JavaScript ES6)

// Object
// one of the JavaScript's data types.
// a collection of related data and/or functionality.
// Nearly all objects in JavaScript are instance of Object
// objeft = { key : value}

// 1. Literals and properties
const obj1 = {}; // 'object literal' syntax
const obj2 = new Object(); // 'object constructor' syntax

function print(person) {
  console.log(person.name);
  console.log(person.age);
}

const ellie = { name: "ellie", age: 4 };
print(ellie);

// with JavaScript magic (dynamically typed language)
// can add properties later
ellie.hasJob = true; // 비추천!
console.log(ellie.hasJob);

// can delete properties later
delete ellie.hasJob;
console.log(ellie.hasJob);

// 2. Computed properties
// key should be always string
console.log(ellie.name); // coding하는 그 순간 key에 해당하는 value를 받아오고 싶을 때 사용한다.
console.log(ellie["name"]); // 정확히 어떤 key가 필요한지 모를 때(즉, runtime에서 결정될 때) 사용한다.
ellie["hasJob"] = true;
console.log(ellie.hasJob);

function printValue(obj, key) {
  //   console.log(obj.key);
  console.log(obj[key]); // ['key']가 아니라 [key]를 사용 했다. 변수로 접근
}

printValue(ellie, "name");
printValue(ellie, "age");

// 3. Property value shorthand
const person1 = { name: "bob", age: 2 };
const person2 = { name: "steve", age: 3 };
const person3 = { name: "dave", age: 4 };
// const person4 = makePerson("ellie", 30);
const person4 = new Person("ellie", 30);
console.log(person4);
// function makePerson(name, age) {
//   return {
//     name: name,
//     age, // key와 value의 이름이 동일하다면 생략 가능
//   };
// }

// 4. Constructor Function
function Person(name, age) {
  // this = {};
  this.name = name;
  this.age = age;
  // return this;
}

// 5. in operator: property existence check (key in obj)
console.log("name" in ellie); // 해당하는 object안에 key가 있는지 확인
console.log("age" in ellie);
console.log("random" in ellie);
console.log(ellie.random);
console.log(ellie.name);
console.log(ellie["name"]);

// 6. for..in vs for..of
// for (key in obj)
console.clear(); // 이전 log들 삭제
for (key in ellie) {
  console.log(key);
}

// for (value of iterable)
const array = [1, 2, 4, 5];
// for (let i = 0; i < array.length; i++) {
//   console.log(array[i]);
// }

for (value of array) {
  console.log(value);
}

// 7. Fun cloning
// Object.assign(dest, [obj1, obj2, obj3...])
const user = { name: "ellie", age: 20 };
const user2 = user;
// user2.name = "coder";
console.log(user);

// old way
const user3 = {};
for (key in user) {
  user3[key] = user[key];
}
console.clear();
console.log(user3);

// new way 1
const user4 = {};
Object.assign(user4, user);
console.log(user4);

// new way 2
const user5 = Object.assign({}, user);
console.log(user5);

// another example
const fruit1 = { color: "red" };
const fruit2 = { color: "blue", size: "big" };
const mixed = Object.assign({}, fruit1, fruit2);
console.log(mixed["color"]);
console.log(mixed.color);
반응형
728x90

6. 클래스와 오브젝트의 차이점(class vs object), 객체지향 언어 클래스 정리 | 프론트엔드 개발자 입문편 (JavaScript ES6)

"use strict";
// Object-oriented 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", "Jobs", -1);
console.log(user1.age);

// 3. Fields (public, private)
// Too soon!
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference
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); // true
console.log(triangle instanceof Rectangle); // false
console.log(triangle instanceof Triangle); // true
console.log(triangle instanceof Shape); // true
console.log(triangle instanceof Object); // true
console.log(triangle.toString());
반응형
728x90

5. Arrow Function은 무엇인가 함수의 선언과 표현   프론트엔드 개발자 입문편(JavaScript ES6)

// Function
// - fundamental building block in the program
// - subprogram can be used multiple times
// - performs a task or calculates a value

// 1. Function declaration
// function name(parm1, param2) { body... return;}
// one function === one thing
// naming: doSomething, command, verb
// e.g. createCardAndPoint -> createCard, createPoint
// function is object in JS
"use strict";

function printHello() {
  console.log("Hello");
}
printHello();

function log(message) {
  console.log(message);
}

log("Hello@2");
log(1234);

// 2. Parameters
// premitive parameters: passed by value
// object parameters: passed by reference
function changeName(obj) {
  obj.name = "coder";
}
const ellie = { name: "ellie" };
changeName(ellie);
console.log(ellie);

// 3. Default parameter (added in ES6)
// function showMessage(message, from) {
//   if (from === undefined) {
//     from = "unknown";
//   }
//   console.log(`${message} by ${from}`);
// }
// showMessage("Hi!");
function showMessage(message, from = "unknown") {
  console.log(`${message} by ${from}`);
}

showMessage("Hi!");

// 4. Rest parameter (add in ES6)
function printAll(...args) {
  // ... 배열 형태로 전달한다.
  for (let i = 0; i < args.length; i++) {
    console.log(args[i]);
  }

  for (const arg of args) {
    console.log(arg);
  }

  args.forEach((arg) => console.log(arg));
}

printAll("dreaqm", "coding", "ellie");

// 5. Local scope (밖에서는 안이 보이지 않고, 안에서민 밖을 볼 수 있다.)
let globalMessage = "global"; // global variable
function printMessage() {
  let message = "hello";
  console.log(message); // local variable
  console.log(globalMessage);
  function printAnother() {
    console.log(message);
    let childMessage = "happy";
  }
  // console.log(childMessage); // error
  return undefined; // 생략 가능
}

printMessage();

// 6. Return a value
function sum(a, b) {
  return a + b;
}
const result = sum(1, 2); // 3
console.log(`sun: ${sum(1, 2)}`);

// 7. Early return, early exit
// bad
function upgradeUser(user) {
  if (user.point > 10) {
    // long upgrade logic...
  }
}

// good (조건이 맞지 않을 때는 바로 return 해서 함수를 종료하고 조건이 맞을때만 로직 실행하도록!)
function upgradeUser(user) {
  if (user.point <= 10) {
    return;
  }
  //long upgrade logic...
}

// First-class function
// functions are treated like any other variable
// can be assigned as a value to variable
// can be passed as an argument to other functions.
// can be returned by another function

// 1. Function expresstion
// a function declaration can be called earlier than it is defined. (hoisted) -> function print() {}
// a function expresstion is created when the execution reaches it. -> const print = funtcion () {}
const print = function () {
  // anonymous function
  console.log("print");
};
print();
const printAgain = print;
printAgain();
const sumAgain = sum;
console.log(sumAgain(1, 3));

// 2. Callback function using function expression
function randomQuiz(answer, printYes, printNo) {
  if (answer === "love you") {
    printYes();
  } else {
    printNo();
  }
}
// anonymous function
const printYes = function () {
  console.log("yes!");
};

// named function
// better debugging in debugger's stack traces
// recursions
const printNo = function print() {
  console.log("no!");
};

randomQuiz("wrong", printYes, printNo);
randomQuiz("love you", printYes, print);

// Arrow function
// always anonymous
// const simplePrint = function () {
//   console.log("simplePrint!");
// };

const simplePrint = () => console.log("simplePrint");
const add = (a, b) => a + b;
const simpleMuliply = (a, b) => {
  // do something more
  return a * b;
};

// IIFE: Immediately Invoked Function Expression
(function hello() {
  console.log("Hello!");
})();

// Fun Quiz time
// function caluate(command, a, b)
// command: add, substract, devide, multiply, remainder

function calculate(command, a, b) {
  if (
    command !== "add" &&
    command !== "substract" &&
    command !== "divide" &&
    command !== "multiply" &&
    command !== "remainder"
  ) {
    console.log("wrong!");
  } else if (command === "add") {
    console.log(`${command}: ${a} + ${b} =`, a + b);
  } else if (command === "substract") {
    console.log(`${command}: ${a} + ${b} =`, a - b);
  } else if (command === "divide") {
    console.log(`${command}: ${a} + ${b} =`, a / b);
  } else if (command === "multiply") {
    console.log(`${command}: ${a} + ${b} =`, a * b);
  } else if (command === "remainder") {
    console.log(`${command}: ${a} + ${b} =`, a % b);
  }
}

calculate("remainder", 5, 2);

// ellie's answer
function calculate(command, a, b) {
  switch (command) {
    case "add":
      return a + b;
    case "substract":
      return a - b;
    case "divide":
      return a / b;
    case "multiply":
      return a * b;
    case "remainder":
      return a % b;
    default:
      throw Error("unknown command");
  }
}

 

반응형
728x90

4. 코딩의 기본 operator, if, for loop 코드리뷰 팁 | 프론트엔드 개발자 입문편 (JavaScript ES6)

// 1. String concatenation
console.log("my" + " cat");
console.log("1" + 2);
console.log(`string literals: 1 + 2 = ${1 + 2}`);

// 2. Numeric operators
console.log(1 + 1); // add
console.log(1 - 1); // substract
console.log(1 / 1); // divide
console.log(1 * 1); // muliply
console.log(5 % 2); // remainder
console.log(2 ** 3); // exponentiation

// 3. Increment and decrement operators
let counter = 2;
const preIncrement = ++counter;
// counter = counter + 1;
// preIncrement = counter;
console.log(`preIncrement: ${preIncrement}, counter: ${counter}`);
const postIncrement = counter++;
// postIncrement = counter;
// counter = counter + 1;
console.log(`preIncrement: ${preIncrement}, counter: ${counter}`);
const preDecrement = --counter;
console.log(`preIncrement: ${preDecrement}, counter: ${counter}`);
const postDecrement = counter--;
console.log(`preIncrement: ${preDecrement}, counter: ${counter}`);

// 4. Assignment operators
let x = 3;
let y = 6;
x += y; // x = x + y;
x -= y;
x *= y;
x /= y;

// 5. Comparison operators
console.log(10 < 6); // less than
console.log(10 <= 6); // less than or equal
console.log(10 > 6); // greater than
console.log(10 >= 6); // greater than or equal

// 6. Logical operators: || (or), && (and), ! (not)
const value1 = false;
const value2 = 4 < 2;

// || (or), finds the first truthy value
console.log(`or: ${value1 || value2 || check()}`); // 심플한 코드를 먼저 실행하게끔 하자

// && (and), finds the first truthy value
console.log(`and: ${value1 && value2 && check()}`); // 심플한 코드를 먼저 실행하게끔 하자

// often used to compress long if-statment
// nullableObject && nullableObject.something
// if (nullableObject != null) {
//   nullableObject.something;
// }

function check() {
  for (let i = 0; i < 10; i++) {
    //wasting time
    console.log("🤩");
  }
  return true;
}

// ! (not)
console.log(!value1);

// 7. Equality
const stringFive = "5";
const numberFive = 5;

// == loose qeuality, with type conversion
console.log(stringFive == numberFive);
console.log(stringFive != numberFive);

// === strict qeuality, no type conversion
console.log(stringFive === numberFive);
console.log(stringFive !== numberFive);

// object equality by reference
const ellie1 = { name: "ellie" };
const ellie2 = { name: "ellie" };
const ellie3 = ellie1;
console.log(ellie1 == ellie2);
console.log(ellie1 === ellie2);
console.log(ellie1 === ellie3);

// equality - puzzler
console.log(0 == false); // true
console.log(0 === false); // false
console.log("" == false); // true
console.log("" === false); // false
console.log(null == undefined); //true
console.log(null === undefined); //false

// 8.  Conditional operators: if
// if, else if, else
const name = "Jongmin Choi";
if (name === "Jongmin Choi") {
  console.log("Welcome, Jongmin Choi!");
} else if (name === " coder") {
  console.log("You are amazing coder");
} else {
  console.log("unknown");
}

// 9. Ternary operator: ?
// condition ? value1 : value2
console.log(name === "Jongmin Choi" ? "yes" : "no"); // 간단히 쓸때만 쓰자

// 10. Switch statement
// use for multiple if checks
// use for enum-like value check
// use for multiple type checks in TS
const browser = "chrome";
switch (browser) {
  case "IE":
    console.log("go away!");
    break;
  case "chrome":
  case "Firefox": // 결과값이 같으면 같이 묶는다.
    console.log("love you!");
    break;
  default:
    console.log("same all!");
    break;
}

// 11. Loops
// while loop, while the condition is trythy,
// body code is executed.
let i = 3;
while (i > 0) {
  //   let j = [];
  console.log(`while: ${i}`);
  //   j.push(i);
  i--;
  //   console.log(j);
}

// do while loop, body code is executed first,
// then check the condition.
do {
  console.log(`dowhile: ${i}`);
  i--;
} while (i > 0);

// for loop, for(begin; condition; step)
for (i = 3; i > 0; i--) {
  console.log(`for: ${i}`);
}

for (let i = 3; i > 0; i = i - 2) {
  // inline variable declaration
  console.log(`inline variable for: ${i}`);
}

// nested loops (cpu에 부담이 간다 좋지 않다.)
for (let i = 0; i < 10; i++) {
  for (let j = 0; j < 10; j++) {
    console.log(`i: ${i}, j: ${j}`);
  }
}

// break, continue
// Q1. iterate from 0 to 10 and print only even numbers (use continue)
let evenNumbers = [];

for (let i = 1; i < 11; i++) {
  if (i % 2 === 1) {
    continue;
  }
  evenNumbers.push(i);
}

console.log(evenNumbers);

// Q2. iterate from 0 to 10 and print numbers until reaching 8 (use break)

let nums = [];

for (let i = 0; i < 11; i++) {
  if (i > 8) {
    break;
  }
  nums.push(i);
}

console.log(nums);
반응형

+ Recent posts