자바스크립트 3-1: Function

수정·2022년 6월 10일
0

1

목록 보기
6/12
post-thumbnail

Function

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

functiton log(message) {
    console.log(message);
    return 0;
}
: 자바스크립트에서는 출력되는 값의 type을 알 수 없다. (이건 Number인지..)

[TypeScipt]
functiton log(message string): number {
    console.log(message);
    return 0;
}
:TypeScipt에서는 return 값을 nember로 출력한다는 것을 코드를 통해 알 수 있다.

2. Parameters

premitive parameters: passed by value
object parameters passed by reference

function changeName(obj) {
    obj.name = 'coder';
}
const sue = { name: 'sue' };
changeName(sue);
console.log(sue);
= name: "coder" 

3. Default parameters (added in ES6)

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

4. Rest parameters (added in ES6)

function printAll(...args) {
    for (let i = 0; i <args.length; i++) {
        console.log(args[i]);
    }
-------------- 간단하게 하려면 ---------------
    for (const arg og args)
     console.log(arg);
--------------더 간단하게 하려면--------------
     args.forEach((arg) => console.log(arg));
}
printAll('sue', 'sujeong' 'coding')
=출력 결과는 sue / sujeong . coding 각각 하나씩 나온다.

5. Local scope

let globalMessage = 'global' // global variable
function printMessage() {
    let message = 'hello';
    console.log(message); // local variable
    console.log(globalMessage);
    function pruntAnother(){
      console.log(message);
      let childMessage = 'hello'; ->자식 함수는 부모 함수에 정의된 변수에 접근을 하면 에러창이 뜬다.
  }
}
printMessage();

:밖에서는 안이 보이지 않고 안에서만 밖을 볼 수 있다.
{블럭}안에 변수를 선언하게 되면 지역 변수
지역적이기 때문에 지연 안에서만 접근이 가능하다.
밖에서 출력하게 되면 에러 발생

6. Return a value

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

7. Early reurn, 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...
    }
}

출처: 드림코딩 자바스크립트 기초 강의 (ES5+)

0개의 댓글