[생활코딩JavaScript] 05일차 노트정리 (함수, 매개변수, 인자, return)

[생활코딩JavaScript] 05일차 노트정리 (함수, 매개변수, 인자, return)

함수예고

함수(Function) : 수납상자, 코드를 정리하기 위한 도구(더 큰 도구는 객체[Object])

생활코딩 //function 키워드를 사용하여 nightDayHandler() 라는 함수를 선언 function nightDayHandler(self) { if (self.value === 'night mode') { //this를 self로 변경 document.querySelector('body').style.backgroundColor = 'black'; document.querySelector('body').style.color = 'white'; self.value = 'day mode'; var alist = document.querySelectorAll('a'); i = 0; while (i < alist.length) { alist[i].style.color = 'yellow'; i += 1; } } else { document.querySelector('body').style.backgroundColor = 'white'; document.querySelector('body').style.color = 'black'; self.value = 'night mode'; var alist = document.querySelectorAll('a'); i = 0; while (i < alist.length) { alist[i].style.color = 'red'; i += 1; } } }

function 함수명(매개변수){}

선언된 함수 사용시 "함수명(매개변수)" 를 입력

함수를 사용함으로 유지보수가 극단적으로 좋아진다.

함수

function countingNumber(){ console.log("1"); console.log("2"); console.log("3"); } countingNumber(); console.log("End"); countingNumber(); console.log("End"); countingNumber(); console.log("End");

결과

매개변수와 인자

함수는 입력과 출력으로 이뤄져 있다.

입력 : 매개변수(Parameter), 인자(argument)

출력 : return

function onePlusOne(){ document.write(1+1); }

여기서 onePlusOne() 함수는 언제나 똑같은 결과를 출력하는 함수입니다.

실행할때 입력값을 입력받도록 하면 조금더 편리하게 다양한 결과값을 도출할 수 있다.

function sum(left, right){ document.write(left + right + ''); } sum(2,3); //5 sum(4,3); //7

sum(left, right)함수는 두가지 변수를 입력하여 다양한 결과를 도출할 수 있다.

이러한 변수를 매개하는 변수 left, right를 매개변수라고 한다.

그리고 sum(2, 3); 에서 함수로 전달하는 2, 3이라는 값을 인자라고 한다.

함수(return 문)

출력 : return

표현식(expression) : 1+1은 숫자 2에 대한 표현식 이다.

function sum2(left, right){ return left + right; } //함수를 실행하면 "left + right" 의 결과값을 출력한다.

계산이라는 기능만을 sum2()함수에 구현함으로써 원자화된 기능을 다양항 맥락에서 사용할 수 있는 자유가 생겼습니다.

이와같이 매개변수를 통해 들어간 값을 return을 통해 출력함으로써 다양한 용도로 활용할 수 있게 됩니다.

from http://ygscoding1193.tistory.com/19 by ccl(A) rewrite - 2021-11-17 06:28:23