png created by here
어떤 한 가지 일을 반복해서 실행할 때 효율적으로 실행하기 위해 실행할 식을 함수로 만든다.
function plushi(name){
return 'hi, '+ name;
}
const greeting = plushi;
console.log(greeting('Jenny'));
console.log(plushi('Jenny'));
//hi, Jenny
//hi, Jenny
{}
부분에 return 을 따로 쓰지 않으면 자동으로 undefined가 반환됨function nothg(a) {}//return undefined; 생략
const blahblah = nothg(0);
console.log(blahblah);
//undefined
function addone(a){
if(a > 10){
return;
}
a += 1;
console.log(a)
}
addone(1);//2
addone(11);//실행되지 않아 결과값 없음
function ex(a,b){
console.log(arguments);
return a*b;
}
ex(3,4)
//[Arguments] { '0': 3, '1': 4, '2': 6, '3': 7 }
//'0'= a, '1' = b
parameter가 arguments에 저장되므로 parameter a,b를arguments[0], arguments[1]
로도 찾을 수 있다
parameter갯수가 정해지지 않았을 때 쓰는 형식으로 출력하면 배열의 형태로 파라미터를 반환
function print(...num){
console.log(num);
}
print(1,2,3,4,5)
//[1,2,3,4,5]
함수 선언문 function a() {}
함수 표현식 const a = function(){}
const a = function red(a){
console.log(a + ' is red');
}
red(apple);
//red is not defined로 오류 발생
const name = ()=>{};
function multiply(a, b){
return a * b;
}
위의 함수는 아래처럼 나타낼 수 있다.
다만 function(){}를 100% 대체할 수 있는 것은 아니다
const multiplay = (a,b) => a * b
console.log(multiply(3,4));
//12
argument(함수를 호출할 때 불러오는 값)로 받아올 수 있는 함수,
외부로부터 주어진 함수= 콜백함수
함수를 반환하는 함수
const is = function(a){
console.log(a + '입니다');
}
const nownumber = function(b){
console.log('지금 숫자 ' + b);
}
function numplay(j, action){
let mynum = action(j);
return mynum;
}
numplay(3, is);//3입니다
numplay(3, nownumber);// 지금 숫자 3
외부로부터 받는 인자를 함수 내부에서 재할당하면 오류날 수 있다.
(특히 object)
fumncion numbers(a){
console.log(a);}
const myproduct = {name: 'xexymix leggings'};
numbers(myproduct);
console.log(myproduct);
function leggings(leggings) {
leggings.name = "xexymix leggings";
console.log(leggings);
}
const temple = { name: "temple" };
leggings(temple);
//{ name: 'xexymix leggings' }
function leggings(leggings) {
console.log(leggings);
}
leggings(temple);
//{ name: 'temple' }