javascript #2 ํ•จ์ˆ˜

๐Ÿถยท2021๋…„ 5์›” 14์ผ
0

๊ฐœ๋… ์ •๋ฆฌ

๋ชฉ๋ก ๋ณด๊ธฐ
2/41

๐Ÿ“์˜ค๋Š˜ ๋ฐฐ์šด ๊ฒƒ

๐Ÿ’ฌ What is function?

์ฝ”๋“œ์™€ ๋ณ€์ˆ˜๋ฅผ ์ €์žฅํ•˜๊ณ  ์žˆ๋Š” ๊ธฐ๊ณ„์ด๋‹ค.
๋ฐ˜๋ณต์ ์œผ๋กœ ์‹คํ–‰๋˜๋Š” ์ผ์ด ํ•„์š”ํ•œ ๊ฒฝ์šฐ์—
ํ•จ์ˆ˜๋กœ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค.

console.log(3*1)
console.log(3*2)
console.log(3*3)
console.log(3*4)
console.log(3*5)
console.log(3*6)
console.log(3*7)
console.log(3*8)
console.log(3*9)

์œ„์™€ ๊ฐ™์€ ์ฝ”๋“œ๋ฅผ ํ•จ์ˆ˜๋กœ ํ‘œํ˜„ํ•œ๋‹ค๋ฉด

function mulTablePrinter(num){
console.log(num*1);
console.log(num*2);
console.log(num*3);
console.log(num*4);
console.log(num*5);
console.log(num*6);
console.log(num*7);
console.log(num*8);
console.log(num*9);
}

๐Ÿ’ฌ What does it mean?

ํ•จ์ˆ˜๋Š” ์ฝ”๋“œ์˜ ๋ฌถ์Œ, ์ฆ๊ฒจ์ฐพ๊ธฐ ๋ฒ„ํŠผ์ด๋‹ค
๋”ฐ๋ผ์„œ ํ•จ์ˆ˜๋Š” ๊ธฐ๋Šฅ์˜ ๋‹จ์œ„๋ผ๊ณ  ๋ณผ ์ˆ˜ ์žˆ๋‹ค
๊ตฌ์ฒด์ ์ธ ์ž…๋ ฅ๊ฐ’๊ณผ ์ถœ๋ ฅ๊ฐ’์„ ๊ฐ€์งˆ ์ˆ˜ ์žˆ๊ณ (mapping)
ํ˜ธ์ถœ ํ›„์—๋Š” ๋ฐ˜๋“œ์‹œ ๋Œ์•„์˜จ๋‹ค(return) (-->ํ•จ์ˆ˜ ๋‚ด๋ถ€์—์„œ return์„ ํ•˜์ง€ ์•Š์€ ๊ฒฝ์šฐ, ์ถœ๋ ฅ๊ฐ’์ด undefined)

๐Ÿ’ฌ How to use?

  1. ๋ฒ„ํŠผ ์ œ์ž‘(ํ•จ์ˆ˜์˜ ์„ ์–ธ)--> ์—ฌ๊ธฐ์„œ param1, param2๋ฅผ '๋งค๊ฐœ๋ณ€์ˆ˜'๋ผ๊ณ  ํ•˜๊ณ 
    function cal(param1, param2){
    console.log(param1+param2);
    return param1*10;
    }

  2. ๋ฒ„ํŠผ ์‚ฌ์šฉ(ํ•จ์ˆ˜์˜ ํ˜ธ์ถœ) --> 10, 20์„ '์ „๋‹ฌ์ธ์ž'๋ผ๊ณ  ํ•œ๋‹ค.
    cal(10, 20);

๐Ÿ’ฌ Evaluation of expressions

let result = cal(10, 20);

function cal(param1, param2){
console.log(param1+param2);
return param1*19;
}

-->

function cal(10, 20){
 console.log(10+20);
 return 10*10;
}

๐Ÿ’ฌ ํ•จ์ˆ˜์˜ ์„ ์–ธ ๋ฐฉ๋ฒ•(to be added)

ํ•จ์ˆ˜ ์„ ์–ธ์‹ vs ํ•จ์ˆ˜ ํ‘œํ˜„์‹ vs ํ™”์‚ดํ‘œ ํ•จ์ˆ˜

  1. ํ•จ์ˆ˜ ์„ ์–ธ์‹
// ํ•จ์ˆ˜ ์„ ์–ธ
function hello (name) {
    console.log(`Hello, ${name}!`);
}

// ํ•จ์ˆ˜ ์‹คํ–‰
hello('Seonkyu');    // Output: Hello, Seonkyu!
  1. ํ•จ์ˆ˜ ํ‘œํ˜„์‹
// ํ•จ์ˆ˜ ํ‘œํ˜„์‹
const hello = function (name = 'stranger') {
    console.log(`Hello, ${name}!`);
}

ํ•จ์ˆ˜ ํ‘œํ˜„์‹์€ ๋ณ€์ˆ˜์ฒ˜๋Ÿผ ๋‹ค๋ค„์ง€๊ธฐ ๋•Œ๋ฌธ์— ์ฝ”๋“œ ๋‚ด์—์„œ ์„ ์–ธํ•œ ์ดํ›„์—๋งŒ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ด๋ฅผ 'ํ˜ธ์ด์ŠคํŒ…' ๋˜์ง€ ์•Š๋Š”๋‹ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค. ๋ฐ˜๋ฉด ํ•จ์ˆ˜ ์„ ์–ธ์‹์œผ๋กœ ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“  ๊ฒฝ์šฐ ํ•จ์ˆ˜์˜ ์œ„์น˜์™€ ์ƒ๊ด€์—†์ด ์–ด๋””์„œ๋“  ํ˜ธ์ถœ ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

  1. ํ™”์‚ดํ‘œ ํ•จ์ˆ˜
const hello = (name) => {
    console.log(`Hello, ${name}!`);
}

๐Ÿ”ฅ ๋” ์ž์„ธํ•œ ๋‚ด์šฉ์€ ์•„๋ž˜ ๋‚ด์šฉ ์ฐธ๊ณ 
https://gonna-be.tistory.com/17
https://velog.io/@bigbrothershin/%EC%98%A4%EB%8A%98-%EA%B3%B5%EB%B6%80%ED%95%A0-%EA%B2%832020.1.30

profile
์šฐ๋‹นํƒ•ํƒ• ๊ฐœ๋ฐœ์ผ๊ธฐ๐Ÿ“๐Ÿค–

0๊ฐœ์˜ ๋Œ“๊ธ€