JavaScript Tutorial.15

ansunny1170·2021년 12월 6일
0
post-thumbnail

JS FUNCTION

  • JS 함수는 특정 작업을 수행하도록 설계된 Block of code다.
    JS 함수는 무언가가 호출할 때 실행된다.

JavaScript Function Syntax

함수매개변수는 함수 정의에서 괄호( )안에 나열 된다. 함수 인수는 호출될 때 함수가 받는 값이다.
함수 내에서 인수(매개변수)는 지역 변수로 작동한다.

Function Return

JS가 return문에 도달하면 함수 실행이 중지된다.
함수가 명령문에서 호출된 경우 JS는 호출 명령문 다음에 코드를 실행하기 위해 "return"한다.
함수는 종종 반환 값을 계산한다. 반환 값은 호출자에게 다시 "return"된다.

Why Functions?

코드를 재사용할 수 있다. 코드를 한번 정의하고 여러번 호출(사용) 가능하다.
다른 인수와 함께 동일한 코드를 여러 번 사용하여 다른 결과를 생성할 수 있다.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Functions</h2>

<p>This example calls a function to convert from Fahrenheit to Celsius:</p>
<p id="demo"></p>

<script>
function toCelsius(f) {
  return (5/9) * (f-32);
}
document.getElementById("demo").innerHTML = toCelsius(77);
</script>

</body>
</html>

The () Operator Invokes the Function

위의 예시(Why Functions?)를 사용하여 toCelsius함수객체를 참조하고 toCelsius()함수결과를 참조한다.
( )없이 함수에 접근하면 함수 결과 대신 함수 객체가 return된다.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Functions</h2>

<p>Accessing a function without () will return the function definition instead of the function result:</p>
<p id="demo"></p>

<script>
function toCelsius(f) {
  return (5/9) * (f-32);
}
document.getElementById("demo").innerHTML = toCelsius;
</script>

</body>
</html>

Functions Used as Variable Values

함수는 모든 유형의 수식, 할당 및 계산에서 변수를 사용하는 것과 동일한 방식으로 사용할 수 있다.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Functions</h2>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
"The temperature is " + toCelsius(77) + " Celsius";

function toCelsius(fahrenheit) {
  return (5/9) * (fahrenheit-32);
} 
</script>

</body>
</html>

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Functions</h2>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
"The temperature is " + x + " Celsius";

function toCelsius(fahrenheit) {
  return (5/9) * (fahrenheit-32);
  
let x = toCelsius();
} 
</script>

</body>
</html>

Local Variables

JS 함수 내에서 선언된 변수는 함수에 대해 LOCAL이 된다.
지역 변수는 함수 내에서만 액세스 할수 있다.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Functions</h2>

<p>Outside myFunction() carName is undefined.</p>

<p id="demo1"></p>

<p id="demo2"></p>

<script>
myFunction();

function myFunction() {
  let carName = "Volvo";
  document.getElementById("demo1").innerHTML =
  typeof carName + " " + carName;
}

document.getElementById("demo2").innerHTML =
typeof carName;
</script>

</body>
</html>



지역 변수는 함수 내에서만 인식되기 때문에 같은 이름의 변수를 다른 함수에서 사용할 수 있다.
지역 변수는 함수가 시작 될 때 생성되고 함수가 완료되면 삭제된다.

profile
공정 설비 개발/연구원에서 웹 서비스 개발자로 경력 이전하였습니다. Node.js 백엔드 기반 풀스택 개발자를 목표로 하고 있습니다.

0개의 댓글