function name(param1, param2) {body... return;}
function printHello(){
console.log("hello");
}
printHello();
//위처럼 작성할수도 있지만 아래처럼 파라미터로 값을 전달하는게 좀 더 효율적인 코드 작성 방식이다.
function log(message) {
console.log(message)
}
function changeName(obj) {
obj.name = 'coder";
//전달 된 obj의 name을 무조건 coder로 전달하는 함수
}
const daniel = {name: "daniel" };
changeName(daniel);
console.log(daniel);
// coder를 출력함
function showMessage(message, from) {
console.log(`${message} by ${from}`);
}
showMessage("Hi");
// Hi by undefined을 출력함
function showMessage(message, from = "unknown") {
console.log(`${message} by ${from}`);
}
showMessage("Hi");
//위처럼 값이 undefined일 때 출력 할 것을 지정해줄수 있다.
//Hi by unknown 출력
function printAll(...args){
for(let i = 0; i < args.length; i++) {
console.log(args[i]);
}
}
printAll('dream', 'coding', 'ellie');
...args로 파라미터를 넘겨 파라미터를 배열 형태로 전달 할 수 있다.
function printAll(...args){
for(const arg of args) {
console.log(arg);
}
}
// or
args.forEach((arg)=> console.log(arg));
//위 두 가지 방법으로도 똑같은 기능을 하는 코드를 작성이 가능하다.
let globalMessage = "global';
// global variable
function printMessage() {
let message= "hello";
console.log(message); // local variable
console.log(globalMessage);
function printAnother() {
console.log(message);
let childMessage = "hello";
// 자식은 부모에서 정의된 message를 받아올 수 있지만, 부모인 PrintMessage는 childMessage를 받아올 수 없다.
}
}
printMessage();
// Bad
function upgradeUser(user) {
if(user.point > 10) {
//long upgrade logic.. very Bad!!
}
}
//Good
function upgraderUser(user){
if(user.point <= 10){
return;
}
}
//값이 undefined, or -1 같은 것들은 빨리 return을 통해 function을 끝내고 다시 logic을 짠다.
//함수의 이름이 없는 것은 anonymous function이라고 한다.
const print = function () {
console.log("print");
};
//함수의 이름이 있으면 named function이라고 한다.
const print = function print() {
console.log("print");
};
print();
// print 출력
const printAgain = print;
printAgain();
// 함수를 변수로 재할당을 할 수 있다 print 출력
const sumAgain = sum;
console.log(sumAgain(1,3));
//4 출력
function randomQuiz(answer, printYes, printNo){
//함수를 전달해서 상황에 맞는 함수를 전달하는 것을 콜백함수라고 한다.
//즉 이 함수는 두 가지의 콜백함수를 갖고있는것이다
if(answer === "love you"){
printYes();
}else{
printNO();
}
}
const simplePrint = function() {
console.log("simplePrint!");
};
//위의 함수를 아래처럼
const simplePrint = () => console.log("simplePrint!");
// 와 같이 간결하게 변경이 가능하다
const add = (a,b) => a + b;
(function hello(){
console.log("IIFE");
})();
위와 같이 ()로 함수를 감싸고 ()로 호출함으로 함수를 바로 실행할 수 있도록 해주는 유용한 기술이다.