JavaScript/드림코딩 엘리 - 자바스크립트 기초 강의 (ES5+)
드림코딩 엘리 - 자바스크립트 기초 강의(ES5+) (5편)
정ㅇr
2021. 11. 11. 13:47
728x90
앞으로 강의를 들으면서 필기는 코드와 함께 작성할 예정. 필요하다면 블로그 글작성 란에도 추가할 것이다. :)
함수 (Function)
// 자바스크립트는 procedural programming language (절차적 프로그래밍 언어)
// function은 sub-program이라고도 함
// 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(param1, param2) { body... return; }
// one function === one thing (하나의 함수는 한가지 일만 처리함)
// naming: doSomething, command, verb (변수는 명사로 이름을 짓지만, 함수는 동작하는 형태로 이름을 지어줘야 한다.)
// e.g. createCardAndPoint -> createCard, createPoint
// function is object in JS (그래서 변수에 담거나, 파라미터 값으로 쓰거나, 리턴 값으로 사용할 수 있다.)
// 파라미터 값이 없는 경우 출력하는 함수
function printHello() {
console.log('Hello');
}
printHello();
// 파라미터 값을 받아서 출력하는 함수
function log(message) {
console.log(message);
}
// 다른 언어처럼 파라미터 값의 type을 지정해주지 않더라도 자바스크립트가 알아서 처리한다.
log('hi');
log(123);
// 참고로 typescriptlang.org 홈페이지의 playground 탭에 들어가면 자바스크립트와 비교해서 코드를 살펴볼 수 있다.
// typescript는 이름처럼 JS와 다르게 param, return값의 type을 명시해줘야 한다.
// 2. Parameters
// primitive parameters(원시 파라미터, 기본형): passed by value
// object parameters: passed by reference
function changeName(obj) {
obj.name = 'coder';
}
const ellie = { name: 'ellie' };
changeName(ellie);
console.log(ellie); // {name: 'coder'}
// obj는 reference로 전달되기 때문에 obj안에 있는 값인 name이 변경되어서 출력된다.
// 3. Default parameters (added in ES6)
function showMessage(message, from = 'unknown') { // 파라미터의 디폴트 값을 다음과 같은 형태로 지정해줄 수 있다.
console.log(`${message} by ${from}`);
}
showMessage('안녕하세요.');
// 4. Rest parameters (added in ES6)
function printAll(...args) { // ... : 배열 형태로 전달됨
for (let i = 0; i < args.length; i++) {
console.log(args[i]);
}
// 배열을 출력할 때의 방법 2
for(const arg of args) {
console.log(arg);
}
// 방법 3
args.forEach((arg) => console.log(arg));
}
printAll('dream', 'coding', 'ellie');
// 참고로 function은 object의 일종이기 때문에 printAll. 을 입력하면 관련된 메소드들을 볼 수 있다.
// 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 = 'hello';
}
// console.log(childMessage);
}
printMessage();
// 참고로 자식 함수가 부모 함수에 정의된 변수들에 접근이 가능한 것을 가리켜 클로저라고 한다.
// 6. Return a value
function sum(a, b) {
return a + b;
}
const result = sum(1, 2); // 3
console.log(`sum: ${sum(1, 2)}`);
// 모든 function은 return undefined 가 들어가 있는 것이라고 볼 수 있다.
// 7. Early return, early exit (조건이 맞지 않을 때는 빨리 조건문을 종료하도록 로직을 짜는 것이 좋음)
// bad case
function upgradeUser(user) {
if (user.point > 10) {
// long upgrade logic ...
}
}
// good case
function upgradeUser(user) {
if(user.pint <= 10) {
return;
}
// long upgrade logic ...
}
함수 표현식, 콜백 함수, 화살표 함수
// Fisrt-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 expression
// a function declaration can be called earlier than it is defined. (hoisted)
// -> 코드에서 함수가 선언되기 이전에도 호출하면 호출이 가능하다.
// a function expression is created when the execution reaches it.
// function () {...}은 function declaration에 해당한다.
// 아래에서 const print는 function expression으로, 할당된 다음에 함수처럼 호출이 가능하다.
const print = function () { // anonymous function (익명 함수) <-> named function
console.log('print');
};
print();
const printAgain = print;
printAgain();
// 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 debuggin in debugger's stack traces
// recursions
const printNo = function print() {
console.log('no!');
// print(); 함수 자기 자신을 호출하는 것은 피보나치 수열을 계산할 때 쓰이기도 함, 계속 호출하면 maximum call stack.. 의 에러문구가 나타난다.
};
randomQuiz('wrong', printYes, printNo);
randomQuiz('love you', printYes, printNo);
// Arrow function
// always anonymous
// const simplePrint = function () {
// console.log('simplePrint!');
// };
const simplePrint = () => console.log('simplePrint!');
const add = (a, b) => a + b;
// arrow function을 원래 함수 형태로 사용할 수 있지만, return 값을 꼭 써줘야 함
const simpleMultiply = (a, b) => {
// do something more
return a * b;
};
// IIFE : Immediately Invoked Function Expression, 함수를 바로 호출할 수 있는 기능
(function hello() {
console.log('IIFE');
})();
출처
https://www.youtube.com/watch?v=e_lU39U-5bQ&list=PLv2d7VI9OotTVOL4QmPfvJWPJvkmv6h-2&index=5
반응형