Function : 함수

Ming·2023년 7월 19일

JavaScript

목록 보기
6/15

function : 함수

👀 function은 반복해서 쓸 수 있는 코드 조각 → 여러번 실행 가능!
👀 {중괄호}안에 작성하는 코드가 함수를 실행할 때 마다 실행된다!
👀 함수 실행은 함수명(소괄호) 을 입력하면 실행된다!
👀 Object안에 함수를 담을 수 있다!(arrow function도 가능)

function 함수명(argument){코드구역} // 함수 선언문
const 변수명 = function(argument){코드구역} // 함수 표현

함수 만드는 법

function 함수명(argument){코드구역}
const 변수명 = function(argument){코드구역}

예시

// 콘솔에서 모두에게 각자 인사하고 싶으면
console.log("hello Hi! a")
console.log("hello Hi! b")
console.log("hello Hi! c")
// 반복되는 단어가 많다...😨

// 😖함수로 만들어보자!
function hello(){
  console.log("hello Hi!");
}

hello();
hello();
hello();
// hello 함수 3번 실행
// -> console에 hello Hi! hello Hi! hello Hi! 3번 출력됨

매개변수

함수 안으로 들어오는 데이터를 받아주는 매개체가 되는 변수
값이 없으면 undefined로 나오며 값이 없으면 = 로 임시값을 적용할 수 있다.

🙋‍♀️hello Hi! 뒤에 a b c 를 출력하려면 함수에게 인수를 보내야 한다
👉인수(argument)는 함수를 실행하는 동안 어떤 정보를 함수에게 보낼 수 있는 방법(여러개 받을 수 있다)

function hello(name, age){
// hello함수의 첫번째 데이터는 name 이라는 변수에게 간다
  console.log(name, age); // hello함수가 실행되면 console에 name과 age를 출력해줘!
}

hello("a",20); // a 20
hello("b",15); // b 15
hello("c"); // c undefined
function plus(a, b=1){
  console.log(a + b);
}

plus(); // NaN
plus(8, 10); // 18
plus(1) // 2

// NaN : Not a Number = 숫자가 아님

🙋‍♀️두 방법이 있는데 차이점은 없나요?
✔️ 호이스팅(Hoisting)에서 차이가 있다!

호이스팅(Hoisting)

함수 선언부가 유효범위 최상단으로 끌어올려지는 현상
❗️함수 선언문에서만 발생하고 함수 표현에서는 발생하지 않는다

hello() // 가능 - 함수 선언을 아래에 했지만 함수 선언이 호이스팅되어 작동된다

function hello(){
  console.log('Hello~')
}

---
hello() // 불가능 - 함수 표현식이라 호이스팅되지 않는다

const hello = function(){
  console.log('Hello~')
}  

Arrow function : 화살표 함수

const 변수명 = (argument)=>{코드구역}

🙋‍♀️기존 function과 다른점이 있나요?
1. 소괄호, 중괄호을 생략하면 return 생략이 가능하다!(파라미터가 하나일 경우)
2. 일반 함수와 비교하면 this의 의미가 다르다!(Arrow function 밖의 의미를 씀!)


예시

// 1. 소괄호, 중괄호, return 생략이 가능하다!(파라미터가 하나일 경우)

const item1 = 1;
const item2 = 2;
const item3 = 3;
const ten = 10;

// function 1 ----------------------------------------------
function additem(items){
  return items + ten;
}

const effect1 = additem(item1) 
const effect2 = additem(item2)
const effect3 = additem(item3)
console.log(effect1,effect2,effect3); // 11, 12, 13

// function 2 ----------------------------------------------
const additem = function(items){
  return items + ten;
}

const effect1 = additem(item1)
const effect2 = additem(item2)
const effect3 = additem(item3)
console.log(effect1,effect2,effect3); // 11, 12, 13

// Arrow function ------------------------------------------
const additem = items => items + ten;

const effect1 = additem(item1)
const effect2 = additem(item2)
const effect3 = additem(item3)
console.log(effect1,effect2,effect3); // 11, 12, 13

+ Object안에 함수를 담기

arrow function도 가능하다!

const nameAll = {
	people : '2',
	firstname : function(){
		return 'kim su young'
	},
	lastname : () => {
		console.log('kim min kyung');
	}
}

console.log(nameAll.firstname()); // kim su young
nameAll.lastname(); //kim min kyung
//함수 자체가 담겼기 때문에 실행()을 해야 한다!

반환 및 종료

return키워드를 사용하면 함수 내부에서 함수 밖으로 데이터를 반환하며, 함수의 동작을 멈추게 한다.
return뒤에 아무것도 작성하지 않으면 암시적으로 undefined가 있다는것과 동일하다

function hello(){
  return console.log('hello 1')
  console.log('hello 2')
}

// 결과적으로 콘솔창에 'hello 1'만 뜬다.
// 'hello 1'을 반환하고 함수를 종료하기 때문에 'hello 2'는 실행되지 않는다

📝 Method

``

1개의 댓글

comment-user-thumbnail
2023년 7월 19일

글 잘 봤습니다, 감사합니다.

답글 달기