프로그래밍/JavaScript

[자바스크립트] Arrow function

choar 2021. 3. 22. 14:39
반응형

드림코딩 엘리 - 자바스크립트 강의 #4

 

  •  Function
    • fundamental building block in the program
    • subprogram can be use 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

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); // => coder

3. Default parameters (added in ES6)

function showMessage(message, from) {
	console.log(`${message} by ${from}`);
}
showMessage('Hi!'); //Hi! by undefined

function showMessage(message, from = 'unknown') {
	console.log(`${message} by ${from}`);
}
showMessage('Hi!'); //Hi! by unknown

4. Rest parameters (added 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('dream', 'coding', 'ellie');

5. Local scope

let globalMessage = 'global'; // global variable
function printMessage() {
   let message = '';
   console.log(message); // local variable
   console.log(globalMessage); // OK
    
   function printAnother() {
      console.log(message); // OK 
      let childMessage = 'hello'; 
   } 
   console.log(childMessage); // error 
}
printMessage();
console.log(message); // error

밖에서는 안이 보이지 않고 안에서만 밖을 볼 수 있다.

6. Return a value

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

return type이 없는 함수들은 return undefined; 가 들어있는 것과 같음

7. Early return, early exit

// bad
function upgradeUser(user) { 
   if (user.point > 10) { 
      // long upgrade logic... 
   } 
} 

// good 
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 Expression

  • a function declaration can be called earlier than it is defined. (hoisted)
  • a function expression is created when the execution reaches it.
const print = function () { // anonymous function (<-> named 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 trace
// recursions
const printNo = function print() {
   console.log('no!');
   print(); // recursion (error, 이렇게 쓰진 않음)
};
randomQuiz('wrong', printYes, printNo); // no!
randomQuiz('love you', printYes, printNo); // yes!

// Arrow function (아래거)
// always anonymous
const simplePrint = function () {
   console.log('simplePrint!');
};
const simplePrint = () => console.log('simplePrint!');
const add = (a, b) => a + b;
const simpleMultiply = (a, b) => {
   // do something more
   return a * b;
};

// IIFE: Immediately Invoked Function Expression
(function hello() {
   console.log('IIFE');
})();
  • printYes, printNo : callback function
반응형