Functions are the main "building blocks" of the program. They allow the code to be called many times without repetition.
We can create functions of our won as well.
function showMessage() {
alert('Hello everyone!');
}
showMeassage();
showMeassage();
This example clearly demonstrates one of the main purposes of functions: to avoid code duplication.
함수 안에 선언된 변수는 오직 함수 안에서만 볼 수 있다.
function showMessage() {
ler message = "Hello, I'm JavaScript!"; // local variable
alert(message);
}
showMessage(); // Hello, I'm JavaScript!
alert(message); // Error!
함수는 밖에서 선언된 외부변수 또한 접근할 수 있다.
let userName = "John";
function showMessage() {
let message = 'Hello, ' + userName;
alert(message);
}
showMessage(); // Hello, John
The function has full access to the outer variable. It can modify it as well.
함수는 외부 변수에 완전히 접근할 수 있다. 함수는 외부변수를 수정할 수도 있다.
만약 같은 이름의 변수가 함수 안에 선언되어 있다면 내부변수는 외부변수를 덮어쓴다.
Variables declared outside of any function are called global.
Global variables are visible from any function.
글로벌 변수의 사용을 최소화하는 것이 좋다.
Sometimes though, they can be useful to store project-level data.
글로벌 변수가 때로는 프로젝트 수준 데이터를 저장하는 데 유용할 수 있다.
We can pass arbitrary data to functions using parameters.
We have variable from and pass it to the function.
*note: the function changes from, but the change is not seen outside, because a function always gets a copy of the value.
함수는 항상 복사된 값을 가지기 때문에 외부에서는 바뀐 것을 볼 수 없다.
*parameter: 매개변수
When a value is passed as a function parameter, it's also called an argument.
값이 매개변수에 전달되면 이것을 또한 인수 라고도 부른다.
In other words, to put these terms straight:
If a function is called, but and argument is not provided, then the corresponding value becomes undefined.
Alternative default parameters
The directive return can be in any place of the function.
When the execution reaches it, the function stops, and the value is returned to the calling code.
It is possible to use return without a value. That causes the function to exit immediately.
값value없이 리턴을 사용할 수 있다. 이 경우 함수는 즉시 빠져나오게 된다.
Functions are actions. So their name is usually a verb. 함수의 이름은 주로 동사이다.
It should be brief, as accurate as possible and describe what the function does, so that someone reading the code gets and indication of what the function does.
함수 이름은 함수가 무슨 일을 하는 지 추측하고 설명할 수 있을 정도로 간결해야하고, 누군가 코드를 읽었을 때 함수의 기능을 알 수 있도록 해야 한다.
Two independent actions usually deserve two functions, even if they are usually called together(in that case we can make a 3rd function that call those two).