예전에 읽었던 The giver도 그렇고 지금 읽고 있는 Gathering Blue도 그렇고....Lois Lowry의 책은 뭐랄까..독특하다. SF 장르인 것 같은데 드러내진 않는다. 지금 읽은 부분까지 보면 The giver와 연결되는 것 같지도 않다.(그럼 왜 Giver Quartet 인거지..?) ....어라? 책 리뷰를 쓰고 있었네.암튼 요즘 영어는 그냥저냥 그렇다. 해외 유투버들이 맥북 M1프로 리뷰를 많이 해줘서 주구 장창 그거만 보고 듣고 있다. 그리고 역시나 들리는 부분만 들리고 안 들리는 데는 안 들린다. 물론 굳이 다시 돌려서 듣거나 하진 않는다. 올해 초에 영어공부를 시작했을때와 지금을 비교해 본다면 확실히 읽기는 어느 정도는 나아진 거 같긴 하다. 듣기도...조금은 더 잘 들린다.
object[key]는 변수로 접근하지만, object.key 및 object['key']는 object(객체)의 property(key)에 접근한다.
example 1
let num = {
one: 1,
two: 2,
};
let one = "two";
console.log(num.one); // result: 1 --> num object에서 one이라는 key의 value 값을 출력한다.
console.log(num["one"]); // result: 1 --> num object에서 one이라는 key의 value 값을 출력한다.
console.log(num[one]); // result: 2 --> one이라는 변수에는 num object의 two라는 key 값이 할당되었기 때문에(??뭔지 좀 이해가 안간다..) num object에서 two라는 key의 value 값을 출력한다.
example 2
const user = { name: "Steve", age: 4 };
function printValue(obj, key) {
// console.log(obj.key); undefined --> user라는 object에는 'key'라는 key값이 없기 때문에 발생
// console.log(obj["key"]); undefined --> 위와 동일
console.log(obj[key]); // ['key']가 아니라 [key]를 사용 했다. 변수로 접근. 즉, 아래 printValue의 "name"과 "age"에 해당하는 key의 value 값을 출력한다.
}
printValue(user, "name"); // result: Steve
printValue(user, "age"); // result: 4
크롬 브라우저의 개발자 도구에서 아래와 같이 코드를 작성하면 조금 특이한 결과 값(?)이 나온다.
개발자 도구에서의 console 창은 어떤 명령에 대한 "결과 값"을 표시해주는 역할을 하는데 printNew 변수를 선언한 문장(const printNew)은 그 자체로는 아무런 결과 값을 보여주지 않기 때문에 undefined(첫번째 빨간 상자)가 출력된다. 두 번째 빨간 상자의 undefined도 console.log() 문장에 대한 동일한 결과라고 볼 수 있다.
그렇다면 초록색 상자는 무슨 의미일까?
초록색 상자의 undefined는 printNew 변수에 할당된 함수의 결과 값중 하나로 봐야 하는 것인가?? 함수가 실행되면 먼저 "print"가 출력되고, 이후에는 console.log("print"); 구문 자체에 대한 결과값으로 "undefined"가 출력된 것으로 이해를 해야 하는건지 궁금하다.
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");
}
}