javascript 함수

chanykim·2021년 7월 23일
0

기본 함수

function printHello(){
	console.log('hello');
}
printHello();

parameter를 포함한 함수

javascript일 때

function printHello(message){
	console.log(message);
}
printHello('hello');

typescript일 때

function printHello(message: string){ //명시적으로 타입을 나타내야 한다.
	console.log(message);
}
printHello('hello');

특정 타입으로 리턴 받고 싶은 함수

함수를 숫자로 리턴받고 싶을 때 아래와 같이 쓴다.

function [함수명](): [return type]{}
let result;

function printHello(message): number{
	console.log(message);
  return 0;
}

result = printHello('hello');
console.log(result); // 0이 나온다.

default parameters 함수

function printIam(name, age = 'unknown'){ //age의 값이 없을 때 default값을 unknown이라 한다.
	console.log(`이름: ${name}, 나이: ${age}`);
}
printIam('chanykim', 29);

rest parameters 함수

function printGame(...args){ //배열형태로 전달된다.
	for (let i = 0; i < args.length; i++)
  		console.log(args[i]);
  	//또다른 방법 1
  	//for (const arg of args)
    //  console.log(arg);
   	//또다른 방법 2
  	//args.forEach((arg) => console.log(arg));
}
printGame('로스트아크', '리그오브레전드', '배틀그라운드');

function expression

const print = function (){ //anonymous function
	console.log('print');
}
print(); // print 출력
const printAgain = print; //function declaration은 hoisting이 가능하다.
printAgain(); //print 출력
//const print = function print(){ //named function
//	console.log('print');
//}

콜백 함수

const printTure = function(){
	console.log('True');
}

const printFalse = function(){
	console.log('False');
}

function trueAndfalse(answer, printTure, printFalse){//function: printTure, printFalse
	if (answer === 'Ture')
      	   printTrue();
  	else
           printFalse();
}
trueAndfalse('True', printTure, printFalse);

화살표 함수

//const simplePrint = function () {
//  console.log('simplePrint');
//}
//const add = function (a, b) {
//  return a + b;
//}

//화살표 함수로 나타내기
const simplePrint = () => console.log('simplePrint');
const add = (a, b) => a + b;
profile
오늘보다 더 나은 내일

0개의 댓글