[Javascript] Javascript 기초 (ES5+) by 드림코딩 4. Function

username_oy·2023년 12월 29일

JavaScript 기초

목록 보기
4/6

1. Function이란..

프로그램 안에서 각각의 작은 단위의 기능들을 실행되는데 이것들을 Function이라 한다.

  • 프로그램속에 핵심적인 기능들이 쌓여있는 구조라고 생각하면 된다.
    fundamental building block in the program

  • subprogram이라고도 불리며 여러 번 재사용이 가능하다.
    subprogram can be used multiple times

  • 한 가지의 tesk나 값을 계산하기 위해 사용되고 있다.

1-1) 정의

function name(param1, param2) { body... return; }

  • 하나의 function에는 한 가지의 일을 하도록
  • 작명 시, doSomething처럼 command형태로 동사로 작명해야한다.
  • function은 object로 간주된다.
function log(message) { //파라미터로 메세지를 전달하면
  console.log(message); // 전달된 메세지를 화면에 출력
}

// TypeScript
function log(message: string) : number { // 타입스크립트는 항상 파라미터나 리턴 타입의 타입을 명시하게 되어 있다.
  console.log(message);
  return 0;
}

전달되어야하는 파라미터와 그의 데이터 타입,그리고 어떤 값이 리턴되는지 확인하고 쓸 수 있다.

1-2) parameters

Javascript 자료형에 Primitive Type(원시 타입)과 Reference Type(주소 타입) 이 두 가지 타입으로 나누어져 있는데
이 둘은 '할당' 과정에서 차이가 존재한다.
Primitive Type은 값(value)자체를 할당하지만, Reference Type은 값이 저장되어 있는 주소를 할당한다.

파라미터 역시 Primitive parameters와 object parameters가 존재하는데
이는 메모리에 value가 그대로 저장되어 있기 때문에 value가 전달되고, object는 메모리에 Reference가 저장된다.

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

1-3) Default parameters

function showMessage(message, from) {
  console.log(`${message} by ${from}`);
}
showMessage('hi!'); // from에는 값이 정의되지 않아 출력 시 undefined로 출력

// 파라미터에 값이 전달되지 않을 경우를 대비하여 사용하지만
  if(from === undefined) {
    from = 'unknown'
  }

// 대신 Default parameters를 사용하여 정의할 수 있다.
function showMessage(message, from ='unknown')

1-4) Rest parameters

function printAll(...args) { // 배열 형태로 전달
  for (let i = 0; i < args.length; i++) {
    console.log(args[i]);
  }
  
  // 더 간단하게 출력하기 위해서
  for(const arg of args) {
    console.log(arg);
  }
}
printAll('kim', 'park', 'lee');

2. Local scope

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

let globalMessage = 'global'; // 글로벌 변수 선언 (global variable)
function printMessage() {
  let localMessage = 'local'; // 지역변수 선언 (local variable)
  console.log(localMessage); // local
  console.log(globalMessage); // global
  functon printAnother() {
    console.log(message); // 부모(printMessage)에게서 정의된 것은 자식인 printAnother에서 확인이 가능하다.
    let childMessage = 'child'; // 하위에서 정의된 childMessage는 상위에서 확인 불가능
}
printMessage();
console.log(localMessage); // ERROR

3. Else if와 Else를 피하고 Early Return

3-1) else if 피하기

else if 문이 앞에 if문과 연결되어 차례대로 실행된다고 생각하면 안된다.
else if 문은 else문 처리가 한 번 되고 if문 동작이 되는 것과 같다.

const x = 1;

if (x >= 0) {
  console.log('x는 0과 같거나 크다');
} else if (x > 0) {
  console.log('x는 0보다 크다');
}
// 'x는 0과 같거나 크다'

if (x >= 0) {
  console.log('x는 0과 같거나 크다');
} else {
  if (x > 0) {
    console.log('x는 0보다 크다');
  }
}

// 위 코드와 아래의 코드는 논리적으로 같으며, 결과도 같다.

else if를 아예 쓰지 말고, 아래 코드처럼 새 if문을 써서 조건을 분리하는 편이 명확하다.

const x = 1;

if (x >= 0) {
  console.log('x는 0과 같거나 크다');
}
if (x > 0) {
  console.log('x는 0보다 크다');
}
// 'x는 0과 같거나 크다'
// 'x는 0보다 크다'

조건이 많아 else if가 늘어나야 할 경우 switch문으로 대체하는 것이 낫다.

3-2) else 피하기

else를 쓰지 않아도 조건이 논리적으로 분리된다.

function getActiveUserName(user) {
  if (user.name) {
    return user.name;
  } else {
    return '이름없음';
  }
}
function getActiveUserName(user) {
  if (user.name) {
    return user.name;
  }
  return '이름없음';
}

else를 쓰지 않아야 하는 이유는 스타일상의 이유도 있지만, 반전된 로직을 작성하게 되는 논리상의 위험성 때문이다.

// age가 20 미만일 시 (미성년자), report라는 특수 함수를 이용하며, 손님에게 인사를 하는 로직
function greetingsCustomer() {
  if (user.age < 20) {
    report(user);
  } else {
    return '안녕하세요';
  }
}

// else 때문에 20세 미만에게만 인사를 하지 않는 의도치 않은 결과가 발생

function greetingsCustomer() {
  if (user.age < 20) {
    report(user);
  }
  return '안녕하세요';
}

// else문을 없애면, 미성년자인지 확인하는 기능과 손님에게 인사하는 두 기능이 분리되어 손님의 나이에 관계없이 인사하는 기능이 실행된다.

3-3) Early Return

조건문에서 먼저 Return할 수 있는 부분은 분리하여 if문 내에서 return하여 함수를 미리 종료하는 것이다.

장점

  • if-else문이 너무 많으면 읽기가 어렵고 조건에 대해 명시적이지 않을 수 있는데, Early Return을 활용하여 리팩토링할 수 있다.
  • 코드를 분리하면 로직은 변함이 없으면서 가독성이 좋고 더 명시적인 코드로 리팩토링할 수 있다.

EX1)

function today(condition, weather, isJob) {
  if (condition === 'GOOD') {
    study();
  	game();
  	SNS();
  	
  	if (weather === 'GOOD') {
      workout();
      cleaning();
    }
    
    if (isJob === 'GOOD') {
      
function today(condition, weather, isJob) {
  if (condition !== 'GOOD') {
    return;
  }
  
  study();
  game();
  SNS();
  	
  if (weather === 'GOOD') {
    workout();
    cleaning();
  }
    
    if (isJob === 'GOOD') {

4. Function Expression

변수와 마찬가지로, 값을 할당할 수 있고
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.

할당이 된 다음부터 선언이 가능하다.
function expression is created when the execution reaches it.

const print = function() {
  console.log('print');
};
print(); // print

4-2) Function declaration

함수가 선언되기 이전에 호출해도 호출이 가능하다.

print(); // print
const print = function() {
  console.log('print');
};

5. Callback Function

상황에 맞게 함수를 호출할 수 있도록 함수의 파라미터에 함수를 전달한 것

function randomQuiz(answer, printYes, printNo) {
  if (answer === 'love you') {
    printYes();
  } else {
    printNo();
  }
}
const printYes = function () { // anonymous function
  console.log('yes!');
};

const printNo = function print() { // named function
  console.log('no!');
};

ramdomQuiz('wrong', printYes, printNo); // no!
ramconQuiz('love you', printYes, printNo); // yes!

6. Arrow function

항상 anonymous를 유지한다.

//EX1
const simplePrint = function () {
  console.log('simplePrint');
};

const simplePrint = () => console.log('simplePrint!');

//EX2
const add = function (a, b) {
  return a + b; 
};

const add = (a, b) => a + b;

7. IIFE: Immediately Invoked Function Expression

함수는 선언을 하고 이름으로 호출을 해야하지만 따로 호출할 필요없이 괄호만 사용하면 호출이 가능하다.

(function hello() {
  console.log('hello!');
})();
profile
프런트엔드 개발자로의 여정

0개의 댓글