티스토리 뷰
1. 함수에 선언과 사용
index7.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>index7.html 파일입니다. </h1>
<script>
/**
* 매개변수(parameter)
* - 함수를 실행하기 위해 필요하다고 지정하는 값
* - 함수를 선언할 때 함수 이름 옆의 괄호 안에 매개변수를 넣는다
*
* 인수(argument)
* - 함수를 실행하기 위해 필요하다고 지정하는 값
* - 함수를 실행할 때 매개변수를 통해서 넘겨주는 값을 인수라 한다.
*
**/
function addNumber(a, b){
let sum = a + b;
return sum;
}
console.log(addNumber(10, 10)); // 20
</script>
</body>
</html>
2. 함수 표현식이란?
자바스크립트에서 "함수 표현식"은 함수를 변수에 할당하는 방식으로 정의하는 것을 의미합니다.
함수 표현식은 함수를 값으로 다루는 함수형 프로그래밍의 개념 중 하나이며, 매우 유용한 패턴 중 하나입니다.
함수 자체가 식(Expression) 이기 때문에 함수를 변수에 할당하거나 함수의 매개변수로 사용할 수 도 있음.
(일급 객체)
index8.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>index8.html 파일입니다. </h1>
<script>
// 1. 매개 변수가 없는 함수 표현식을 정의해보자.
// function()는 익명이지만 currentTime에 담김.
const currentTime = function(){
const now = new Date();
return now.toLocaleTimeString(); // 지역 시간을 string 으로 변환
}
// 출력 결과를 잘 확인해보자.
console.log(currentTime); // function(){}(중괄호) 코드 전체 출력
console.log(currentTime());
console.log('----------------------');
// 주의! 결과에 대한 분석을 통해 이해해보자.
// 1)
console.log(currentTime());
// 2)
const time = currentTime(); // string 값이 time 에 담김
console.log(time);
// 2. 매개변수가 있는 함수 표현식
const add = function(x, y){
return x + y;
}
console.log(add(3, 5)); // 8
// 함수 표현식 x (값 임.)
const result = add(10, 20);
console.log(result); // 30
</script>
</body>
</html>
'JS' 카테고리의 다른 글
JavaScript(Browser Object Model) (0) | 2024.07.23 |
---|---|
JavaScript(Document Object Model; DOM) (0) | 2024.07.22 |
JavaScript(객체와 배열) (0) | 2024.07.19 |
JavaScript(데이터 타입 및 연산) (0) | 2024.07.18 |
JavaScript 사전 기반 지식 (0) | 2024.07.18 |