함수 : 컴퓨터에게 일을 시키기위한 지시사항의 묶음
(입력input => 함수f() => 출력output의 과정으로 이루어져있음)
함수선언식 : function을 이용해 함수를 만든다
ex) f(x) = x + 1 // -> x + 1은 함수의 ation
y = f(x) 이고 x = 2 일때, y = ?
f(2) = 2 + 1 = y // 즉, y = 3 이 된다.
ex) f(x) = x에 들어가는 문자열의 길이
f(hello) = 5
f(반가워) = 3
수학적인 표현 f(hello) 이라면
Javascript에서는 getLength('hello') // getLength는 함수의 이름, '' 문자열표기
ex)
let length = getLength('hello');
console.log(length); // 5
- 함수의 선언 : 함수선언식을 만드는 일
function functionName(input*){ // computer is doing }
함수 표현식은 아래와 같이 정의할 수 있다.
let function = function(input*){ // computer is doing }
*매개변수input : 특별히 함수에서 사용할 입력값. 함수 실행 시 입력에 따라 바뀔 수 있는 변수이다. 변수이나 let등의 키워드를 쓰지않고 사용할 수 있다.
ex) 집까지 걸리는 시간을 계산하는 함수
let timeToGoHome = function(speed, distance){
let time = distance / speed;
console.log(time);*
} // timeToGoHome이라는 함수를 만들었다.
timeToGoHome(20, 100) // 5
*console.log() : 디버깅 및 확인용 기능을 담당하는 함수. 함수 바깥으로 결과를 가져오려면 return 을 해야한다.
(return : 함수 밖으로 결과를 반환한다.)
ex) console.log() return
let timeToGoHomeOne = function(speed, distance){
let time = distance / speed;
console.log(time);
}
timeToGoHomeOne 함수를 사용하여 낸 견과를 사용하고 싶을 때,
timeOne = timeToGoHome(20, 100) // 5 가 나오지만
timeOne 을 따로 검색하면 값은 undefined 가 나온다.
이는 위의 함수에서 값을 return 하지 않았기 때문이다.
let timeToGoHomeTwo = function(speed, distance){
let time = distance / speed;
return time;
}
timeToGoHomeTwo 함수를 사용하면
timeTwo = timeToGoHome(10, 100) // 10 이 나오고
timeTwo // 10 변수만 검색 했을 때도 값이 나온다.
console.log(time)를 return time으로 바꿨기때문이다.