Function이란?
계속 반복해서 사용할 수 있는 코드 조각
어떤 코드를 캡슐화해서, 실행을 여러 번 가능하게 해준다.
(실행되고 나면) 사라지고, 마지막엔 결과를 남기게 한다.
기본
function sayHello() {
// 실행하게 될 코드 블록
console.log("Hello"):
}
sayHello("Hello")
sayHello("Hello")
sayHello("Hello")
절차 (1) Function안으로 값이나 데이터를 보내는 방법
function sayHello() {
console.log("Hello my name is A");
}
sayHello("jiyoung");
sayHello("gyeogmi");
sayHello("junhan");
콘솔창에는 Hello my name is A 가 3번 뜰 것이다.
절차 (2) Function안에서 보낸 값이나 데이터를 받아오는 방법
function sayHello(nameOfPerson) {
console.log(nameOfPerson);
}
//jiyoung, gyeongmi,junhan을 argument(인수)라고 한다.
sayHello("jiyoung");
sayHello("gyeogmi");
sayHello("junhan");
()에 데이터를 추가한다.
그 데이터에는 어떤 variable이든, 어떤 이름이든 만들어서 넣는다.
argument(인수) : function을 실행하는 동안 어떤 정보를 function에게 보낼 수 있는 방법이다.
예제1.
// argument를 받음.(nameOfPerson, age)
function sayHello(nameOfPerson, age) {
console.log("Hello my name is " + nameOfPerson + " and I'm " + age);
}
// argument를 보내고(3가지)
sayHello("jiyoung", 24);
sayHello("gyeogmi", 51);
sayHello("junhan", 55);
예제2.
function plus(firstNumber, secondNumber) {
console.log(firstNumber + secondNumber);
}
function divide(a, b) {
console.log(a / b);
}
plus(45, 2);
divide(30, 2);
예제3. (심화) function이 object안에서 가능할 때만 가능
// function이 object안에서 가능할 때
const player = {
name: "nico",
sayHello: function (otherPersonsName) {
console.log("hello! " + otherPersonsName + "nice to meet you!");
},
};
// on object
console.log(player.name);
// plus function (==array.push)
player.sayHello("jiyoung ");
player.sayHello("gyeongmi ");
계산기 만들기
const calculator = {
add: function (a, b) {
console.log(a + b);
},
minus: function (a, b) {
console.log(a - b);
},
div: function (a, b) {
console.log(a / b);
},
multi: function (a, b) {
console.log(a * b);
},
powerOf: function (a, b) {
console.log(a ** b);
},
};
calculator.add(55, 3);
calculator.minus(15, 3);
calculator.div(48, 4);
calculator.multi(9, 6);
calculator.powerOf(2, 3);
예제1. 경고창 뜨게 만들기
const calculator = {
add: function (a, b) {
alert(a + b);
},
minus: function (a, b) {
alert(a - b);
},
div: function (a, b) {
alert(a / b);
},
multi: function (a, b) {
alert(a * b);
},
powerOf: function (a, b) {
alert(a ** b);
},
};
calculator.add(55, 3);
calculator.minus(15, 3);
calculator.div(48, 4);
calculator.multi(9, 6);
calculator.powerOf(2, 3);
예제2. 코드에서 결과값 나타나게 하기
ex. 나의 한국 나이를 계산하는 외국인일 경우, Return이용(Function안과 밖을 소통하고자)
const age = 96;
function calculateKrAge(ageOfForeigner) {
return ageOfForeigner + 2;
}
const krAge = calculateKrAge(age);
console.log(krAge);
98 이라고 뜰 것이다.
const age = 96;
function calculateKrAge(ageOfForeigner) {
ageOfForeigner + 2;
return "hello";
}
const krAge = calculateKrAge(age);
console.log(krAge);
hello 이라고 뜰 것이다.
이처럼, Return의 역할은
function 안에서 무언가를 return해서,
누군가 그 function을 실행할 때, 해당 function의 return 값으로 대체
즉, Function안의 반환 값과 같은 variable을 console.log로 하고 있다.
Function외부에서 value 도출해내고 싶을 때 쓰임.
- 중요한 개념!
const calculator = {
add: function (a, b) {
return a + b;
console.log("hello");
},
minus: function (a, b) {
return a - b;
},
div: function (a, b) {
return a / b;
},
multi: function (a, b) {
return a * b;
},
powerOf: function (a, b) {
return a ** b;
},
};
const addResult = calculator.add(2, 3);
콘솔창엔 뜨지 않는다.
▶한번 return하면 function 작동을 멈추고 결과 값을 return하고 끝나버린다. : 마지막줄에 return이 있으면 그 다음줄에 어떤 console.log사항, 기타사항이 있더라도 그 즉시 종료되어 그 다음 console.log 값은 나타나지 않는 것!
return까지만 작동한다.
앞의 계산기 만든 코드에 다시 적용을 한다면,
const calculator = {
add: function (a, b) {
return a + b;
},
minus: function (a, b) {
return a - b;
},
div: function (a, b) {
return a / b;
},
multi: function (a, b) {
return a * b;
},
powerOf: function (a, b) {
return a ** b;
},
};
const addResult = calculator.add(2, 3);
const minusResult = calculator.minus(plusResult, 10);
const divideResult = calculator.div(10, minusResult);
const multiResult = calculator.multi(divideResult, minusResult);
const powerOfResult = calculator.powerOf(divideResult, plusResult);
console.log(plusResult, minusResult, divideResult, multiResult, powerOfResult);
'개발언어 > JavaScript' 카테고리의 다른 글
JavaScript - 브라우저(Document, Elements, Events) (0) | 2021.08.26 |
---|---|
Conditionals : 조건문 (if,else) (0) | 2021.08.25 |
Objects [설명이 필요한 정보가 담긴 데이터 리스트들] (0) | 2021.08.24 |
Array [설명이 필요하지 않은 데이터 리스트들] (0) | 2021.08.24 |
Booleans(true,false,null, undefined) (0) | 2021.08.24 |