λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°

Frontend Dev/JavaScript

ν•¨μˆ˜μ˜ λ§€κ°œλ³€μˆ˜(parameter)와 인수(argument μ „λ‹¬μΈμž)

λ°˜μ‘ν˜•

πŸ‘Ύ λ§€κ°œλ³€μˆ˜(parameter)

 ν•¨μˆ˜μ˜ λ§€κ°œλ³€μˆ˜λž€ ν•¨μˆ˜μ˜ μ •μ˜μ—μ„œ 전달받은 인수λ₯Ό ν•¨μˆ˜ λ‚΄λΆ€λ‘œ μ „λ‹¬ν•˜κΈ° μœ„ν•΄ μ‚¬μš©ν•˜λŠ” λ³€μˆ˜λ‘œ μ „λ‹¬λœ λ§€κ°œλ³€μˆ˜λŠ” ν•΄λ‹Ή ν•¨μˆ˜μ˜ μ§€μ—­λ³€μˆ˜κ°€ λœλ‹€.

 

 πŸ’¬ μžλ°”μŠ€ν¬λ¦½νŠΈμ—μ„œ ν•¨μˆ˜λ₯Ό μ •μ˜ν•  λ•ŒλŠ” λ§€κ°œλ³€μˆ˜μ˜ νƒ€μž…μ„ λ”°λ‘œ λͺ…μ‹œν•˜μ§€ μ•ŠλŠ”λ‹€. ν•¨μˆ˜λ₯Ό ν˜ΈμΆœν•  λ•Œλ„ 인수둜 μ „λ‹¬λœ 값에 λŒ€ν•΄ μ–΄λ– ν•œ νƒ€μž… 검사도 ν•˜μ§€ μ•ŠλŠ”λ‹€. ν•¨μˆ˜λ₯Ό ν˜ΈμΆœν•  λ•Œ ν•¨μˆ˜μ˜ μ •μ˜λ³΄λ‹€ 적은 수의 μΈμˆ˜κ°€ μ „λ‹¬λ˜λ”λΌλ„, λ‹€λ₯Έ μ–Έμ–΄μ™€λŠ” 달리 였λ₯˜λ₯Ό λ°œμƒμ‹œν‚€μ§€ μ•Šκ³ , μ „λ‹¬λ˜μ§€ μ•Šμ€ λ‚˜λ¨Έμ§€ λ§€κ°œλ³€μˆ˜μ— μžλ™μœΌλ‘œ undefined 값을 μ„€μ •ν•œλ‹€.

function greeting(name) {
  console.log("hello, " + name);
}

greeting("Anna"); // hello, Anna

 

πŸ‘©πŸ»‍πŸ’» example

function getUser (number) {
  let userName = 'fay';
};

console.log(number); // Uncaught ReferenceError: number is not defined
console.log(userName); // Uncaught ReferenceError: userName is not defined

 → λ§€κ°œλ³€μˆ˜λŠ” ν•¨μˆ˜ λ‚΄λΆ€μ—μ„œλ§Œ μ‚¬μš© κ°€λŠ₯ν•˜λ‹€. (ν•¨μˆ˜ λ‚΄λΆ€μ—μ„œ μ„ μ–Έν•œ λ³€μˆ˜λ„ ν•¨μˆ˜ λ‚΄λΆ€μ—μ„œλ§Œ μ‚¬μš©μ΄ κ°€λŠ₯ν•˜λ‹€)

 

function getUserName (user1, user2) {
  console.log(user1);
  console.log(user2);
};

getUserName('fay'); // 'fay', undefined
function addNum(x, y, z) {
  return x + y + z;
}

console.log( addNum(1, 2, 3) ) // 6 
console.log( addNum(1, 2) ) // NaN

 → λ§€κ°œλ³€μˆ˜μ˜ μˆ˜λ³΄λ‹€ 적은 μΈμˆ˜κ°€ μ „λ‹¬λ˜λ©΄, 아무것도 μ „λ‹¬λ˜μ§€ μ•Šμ€ λ§€κ°œλ³€μˆ˜λŠ” undefined둜 μ΄ˆκΈ°ν™” λœλ‹€.

 λ””ν΄νŠΈ λ§€κ°œλ³€μˆ˜λ₯Ό μ‚¬μš©ν•΄ ν•¨μˆ˜λ₯Ό ν˜ΈμΆœν•  λ•Œ λͺ…μ‹œλœ 인수λ₯Ό μ „λ‹¬ν•˜μ§€ μ•Šμ•˜μ„ κ²½μš°μ— μ‚¬μš©ν•˜κ²Œ 될 기본값을 μ„€μ •ν•  수 μžˆλ‹€.

 

 λ””ν΄νŠΈ λ§€κ°œλ³€μˆ˜λž€?

 

λ””ν΄νŠΈ λ§€κ°œλ³€μˆ˜μ™€ λ‚˜λ¨Έμ§€ λ§€κ°œλ³€μˆ˜ (with arguments 객체)

λ””ν΄νŠΈ λ§€κ°œλ³€μˆ˜(default parameter)와 λ‚˜λ¨Έμ§€ λ§€κ°œλ³€μˆ˜(rest parameter)λŠ” ECMAScript 6λΆ€ν„° μΆ”κ°€λ˜μ—ˆλ‹€. 이전 λ²„μ „μ˜ μžλ°”μŠ€ν¬λ¦½νŠΈμ—μ„œλŠ” ν•¨μˆ˜μ—μ„œ λ§€κ°œλ³€μˆ˜μ˜ 개수λ₯Ό λ™μ μœΌλ‘œ μ²˜λ¦¬ν•˜κΈ° μœ„ν•΄ arguments 객체

fay-story.com

 

 

πŸ‘Ύ 인수(argument μ „λ‹¬μΈμž)

 μΈμˆ˜λž€ ν•¨μˆ˜λ₯Ό ν˜ΈμΆœν•  λ•Œ λ§€κ°œλ³€μˆ˜μ— μ „λ‹¬λ˜λŠ” 값을 λ§ν•œλ‹€.

function greeting(name) { // name은 λ§€κ°œλ³€μˆ˜(parameter)
  console.log("hello " + name);
}

greeting("fay"); // "fay"λŠ” 인수(argument)

 


✏️ κ³΅λΆ€ν•˜λ©° μ •λ¦¬ν•œ λ‚΄μš©μž…λ‹ˆλ‹€. 잘λͺ»λœ μ •λ³΄λ‚˜ 더 κ³΅μœ ν•  λ‚΄μš©μ΄ 있으면 λŒ“κΈ€λ‘œ μ•Œλ €μ£Όμ„Έμš”!

μ½μ–΄μ£Όμ…”μ„œ κ°μ‚¬ν•©λ‹ˆλ‹€ 😊

λ°˜μ‘ν˜•