๐Ÿ‘ฉโ€๐Ÿ’ปTIL5. Vanilla JS : First Function!

Lilyยท2021๋…„ 5์›” 18์ผ
0

Today I Learned

๋ชฉ๋ก ๋ณด๊ธฐ
5/30
post-custom-banner

์•„๋ž˜ ๊ธ€์€ ๋…ธ๋งˆ๋“œ์ฝ”๋” '๋ฐ”๋‹๋ผ JS๋กœ ํฌ๋กฌ ์•ฑ ๋งŒ๋“ค๊ธฐ'๋ฅผ ์ˆ˜๊ฐ•ํ•˜๋ฉฐ ๋ฐฐ์šด ์ ์„ ์ •๋ฆฌํ•œ ๊ธ€์ž…๋‹ˆ๋‹ค.

๐ŸŽ† Function(ํ•จ์ˆ˜)

ํ•จ์ˆ˜๋ž€ ํ•˜๋‚˜์˜ ๋กœ์ง์„ ์žฌ์‹œํ–‰ํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•˜๋Š” ๊ฒƒ์œผ๋กœ ์ฝ”๋“œ์˜ ์žฌ์‚ฌ์šฉ์„ฑ์„ ๋†’์—ฌ์ค€๋‹ค. - ์ƒํ™œ์ฝ”๋”ฉ -

- ํ•จ์ˆ˜ ์ •์˜ ๋ฐฉ๋ฒ•

function ํ•จ์ˆ˜๋ช…() { 

}

ํ•จ์ˆ˜๋Š” function ๋’ค์— ํ•จ์ˆ˜์˜ ์ด๋ฆ„์ด ์˜ค๊ณ , ()์†Œ๊ด„ํ˜ธ๊ฐ€ ๋”ฐ๋ผ์˜จ๋‹ค. ์†Œ๊ด„ํ˜ธ์— ์ธ์ž(argument)๋ผ๋Š” ๊ฐ’์ด ์ฐจ๋ก€๋กœ ๋“ค์–ด์˜ค๋Š”๋ฐ ์ด ๊ฐ’์€ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•  ๋•Œ ํ•จ์ˆ˜์˜ ๋กœ์ง์œผ๋กœ ์ „๋‹ฌ๋  ๋ณ€์ˆ˜(parameter)๋‹ค. ์ธ์ž๋Š” ์ƒ๋žต ํ•  ์ˆ˜ ์žˆ๋‹ค. ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœ ํ–ˆ์„ ๋•Œ ์‹คํ–‰ํ•˜๊ฒŒ ๋  ๋ถ€๋ถ„์ด {}์ค‘๊ด„ํ˜ธ ์•ˆ์ชฝ์— ์˜จ๋‹ค. -์ƒํ™œ์ฝ”๋”ฉ-

๐ŸŽ† argument(์ธ์ž)์™€ parameter(๋งค๊ฐœ๋ณ€์ˆ˜)

function sayHello(name,age){
  console.log("Hello" ,name, ", you are", age, " years old!")
}

sayHello("yeji", 27)

//Hello yeji, you are 27 yeas old!

sayHelloํ•จ์ˆ˜๋Š” ๋‘๊ฐœ์˜ ๋งค๊ฐœ๋ณ€์ˆ˜(parameter) name๊ณผ age๋ฅผ ๊ฐ–๋Š”๋‹ค. sayHello("yeji",27)๋Š” "yeji"์™€ 27์„ ์ž…๋ ฅ ๊ฐ’์œผ๋กœ ๋ฐ›์•„, Hello yeji, you are 27 years old ๋ผ๋Š” ๊ฐ’์„ ์ถœ๋ ฅํ•œ๋‹ค. ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ ์ž…๋ ฅ๋˜๋Š” ๊ฐ’์„ ์ธ์ž(argument)๋ผ ํ•œ๋‹ค. ๊ทธ๋Ÿฐ๋ฐ ๋ณดํ†ต์€ parameter์™€ argument๋ฅผ ๊ตฌ๋ถ„์—†์ด ์‚ฌ์šฉํ•œ๋‹ค.

๐ŸŽ† string์„ ๋” ๊ฐ„ํŽธํ•˜๊ฒŒ ์“ฐ๋Š” ๋ฐฉ๋ฒ•! - `(๋ฐฑํ‹ฑ)์‚ฌ์šฉ

function sayHello(name,age){
  console.log(`Hello ${name}, you are ${age} years old!`)
}

sayHello("yeji", 27)

//Hello yeji, you are 17 yeas old!

''๋‚˜ ""๋กœ string์„ ์“ฐ๋ฉด ๋„์–ด์“ฐ๊ธฐ๋ฅผ ์œ ์˜ํ•˜๊ณ , ๋”ฐ์˜ดํ‘œ๋ฅผ ๋ฐ˜๋ณตํ•ด์•ผํ•˜๋ฏ€๋กœ ๊ธดstring์„ ์“ธ ๊ฒฝ์šฐ ๋ถˆํŽธํ•  ์ˆ˜ ์žˆ๋‹ค. ๊ทธ๋ž˜์„œ ๋‚˜์˜จ ๊ฒƒ์ด ๋ฐฑํ‹ฑ(``)์„ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•์ด๋‹ค.

๐Ÿ”ฅ console.log ์™€ return ์˜ ์ฐจ์ด

์ด๋ฒˆ์— ๊ณต๋ถ€ํ•˜๋ฉด์„œ ๊ฐ€์žฅ ์ดํ•ดํ•˜๊ธฐ ์–ด๋ ค์› ๋˜ ๋ถ€๋ถ„์ด๋‹ค.

ํ•ต์‹ฌ์€ " console.log๋Š” ์ฝ˜์†”์ฐฝ์— show๋ณด์—ฌ์ค„ ๋ฟ, ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜์ง€๋Š” ์•Š๋Š”๋‹ค. return์€ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜๊ณ  ํ•จ์ˆ˜๋ฅผ ์ข…๋ฃŒ์‹œํ‚จ๋‹ค. "

์—ฌ๊ธฐ์„œ greet์ด๋ผ๋Š” ๋ณ€์ˆ˜๋Š” sayHelloํ•จ์ˆ˜์˜ return๊ฐ’์œผ๋กœ ์ •์˜ ๋˜์—ˆ๋‹ค. 5๋ฒˆ์ค„์˜ ์‹คํ–‰์— ๋”ฐ๋ผ ์ฝ˜์†”์ฐฝ์— "Hello yeji, you are 27 years old!"๊ฐ€ ๋ณด์—ฌ์ง„๋‹ค. ๋ฐ˜๋ฉด 6๋ฒˆ์ค„์˜ console.log() ๋Š” undefined๋œ๋‹ค. ์™œ๋ƒํ•˜๋ฉด sayHello์˜ return๊ฐ’ ์ž์ฒด๊ฐ€ ์—†๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. sayHelloํ•จ์ˆ˜๋Š” console์ฐฝ์— ๊ธ€์„ ์ฐ์–ด๋‚ผ๋ฟ, ๊ฐ’์„ returnํ•˜์ง€๋Š” ์•Š๋Š”๋‹ค.

greet์ด undefined๊ฐ€ ๋˜์ง€ ์•Š์œผ๋ ค๋ฉด ์•„๋ž˜์™€ ๊ฐ™์ด console.log๋Œ€์‹  return์„ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค.

๐ŸŽ† object๋กœ ํ•จ์ˆ˜ ์ •์˜ ํ•˜๊ธฐ


object๋ฅผ ์ด์šฉํ•ด ์ด๋Ÿฐ ๋ฐฉ๋ฒ•์œผ๋กœ๋„ ํ•จ์ˆ˜๋ฅผ ์ •์˜ํ•˜๊ณ  ์‚ฌ์šฉ ํ•  ์ˆ˜ ์žˆ๋‹ค.

profile
i๐ŸŽS ๊ฐœ๋ฐœ์„ ํ•ฉ๋‹ˆ๋‹ค
post-custom-banner

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