일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 드림코딩
- useImperativeHandle
- useState
- 리액트작동원리
- realDOM
- 제어컴포넌트
- useContext
- eventloop
- js
- BIND
- ForwardRefs
- flexbox
- reactPortals
- useReducer
- useCallback
- SQL
- virtualDOM
- mysql
- 재귀함수
- CSS
- reactDOM
- MariaDB
- vscode
- useEffect
- hoisting
- 비제어컴포넌트
- 변수타입
- React
- ConnectBy
- 프로그래머스
Archives
- Today
- Total
SOOM_BLOG [숨숨 블로그]
[Javascript] Function 선언과 표현 (feat. 드림코딩 by 앨리) 본문
Function
- fundamental building block in the program
- subprogram can be used multiple times
- performs a task or calculates a value
Function declation
- function name (param1, param1) {body ... return;}
- one function === one thing : 함수 하나는 한 가지 일만 해야한다.
- naming : doSomething, command, verb
- function is object in JS
Parameters
- premitive parameters : passed by value
- object parametser : passed by reference ☆☆
Default Parameters (added in ES6)
- parameter 옆에 default 값을 지정.
function showMessage (message, from = 'unknown') { console.log(`${message} by ${from}`); }
Rest Parameters (added in ES6)
- parameter가 배열 형태로 전달된다.
function printAll(...args) { for (const arg of args) { console.log(arg); } } printAll('dream', 'coding', 'ellie'); // dream coding ellie
Local Scope
❗️ 자바스크립트에서 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); // error! } printMessage(); // hello global console.log(message); // error!
Return a value : return이 정의되지 않은 함수는 'return undefined'가 default이다.
Early return, early exit
조건이 맞지 않는 경우, 값이 undefined인 경우, 값이 -1인 경우 등등 --> 빨리 return하고, 아닌 경우의 로직을 타게끔 작성하는 것이 좋음.// bad function upgradeuser(user) { if (user.point > 10) { // long upgrade logic... } } //good function upgradeuser2(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 function : 파라미터 전달이 되며
- can be returned by another function : 리턴 값으로도 리턴이 된다.
Function Expression
- a function declaration can be called earlier than it is defined. (hoisted)
function declaration은 함수가 선언되기 이전에 호출해도 가능하다. 자바스크립트 엔진이 선언된 것을 제일 위로 올려주기 때문이다. - a function expression is created when the execution reaches it.
function expression은 할당된 다음부터 호출이 가능하다.
print(); // error, function expression은 할당된 다음부터 호출이 가능. //function expression const print = funtion () { // 함수에 이름이 없는 경우 : anonymous function console.log('print'); } const test = funtion testFunction() { // 함수에 이름을 지정해준 경우 : named function console.log('print'); } print(); // print const printAgain = print; // 다른 변수에 할당 가능. printAgain(); // print sum(1,2); // 3, function declaration은 선언 이전에 호출 가능! (호이스팅) //function declaration function sum (num1, num2) { console.log(num1+num2); }
- a function declaration can be called earlier than it is defined. (hoisted)
Callback function using function expression
함수를 전달해서 원하는 상황에 호출하게 하는 것을 Callback function이라고 한다.//Callback functions : printYes, printNo 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 debuger's stack traces : 디버깅할 때 더 편함 // - recursions : 재귀함수 가능 const printNo = function print() { console.log('no!'); } randomQuiz('wrong', printYes, printNo); // no! randomQuiz('love you', printYes, printNo); // yes!
Arrow function : always anonymous function
- 가독성이 더 좋다.
- 상위 환경에서의 this를 참조한다.
// Arrow function 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'); })(); // IIFE
참고 영상
'TIL > js' 카테고리의 다른 글
[Javascript] data types, let vs var, hoisting (feat. 드림코딩 by 엘리) (0) | 2022.03.22 |
---|---|
[Javascript] Direct(직접) vs Indirect(간접적) 함수 실행 (0) | 2022.03.12 |
[Javascript] 정규 표현식_특수문자, 패턴정리 (0) | 2022.03.07 |
[Javascript] Function.prototype.bind() (0) | 2022.02.17 |
[Javascript] EVENT LOOP란? (feat. 코딩애플) (0) | 2022.01.20 |