드림코딩 엘리 JS 기초 강의 재구성한 내용입니다.
function 함수이름(파라미터1, 파라미터2) {
설정할 코드
return;
}
function 이름은 명령형 동사로 만드는 것이 좋다
function은 참고로 object다
function 공부하다가 파라미터가 나오는데'파라미터가 뭐지??'싶어서
구글링을 하다가 안되서 유튜브에서 검색했는데 '코딩애플'님의 파라미터 설명을 보고 마침내 이해를 하게 되었다
(덩달아 function의 기능도 잘 이해할 수 있었다!!
function은 파라미터 없이 쓸수도 있지만 파라미터를 만들면 함수 이름(입력할 내용);
으로 간단하게 여러가지를 실행할 수 있게된다는 장점이 있다. 심지어 function(파라미터1, 파라미터2, 파라미터3...)파라미터 여러개를 쓸 수 있다
는 내용을 알게 되었다)
더 이상 나누어질 수 없는 파라미터, 가장 기본의 파라미터
(premitive 원시의)
number, string, boolean(true/false), null, undefined, symbol가 이에 해당한다.
미지수 x,y처럼 대상이 되는 매개변수
정해지지 않은 대입할 파라미터를 쓸 때 씀
function AddOne(ParameterObj, ParameterDef=undefined) {
ParameterObj = ParameterObj + 1;
console.log(ParameterObj, ParameterDef);
}
AddOne(3);
// 출력: 4 undefined
/* ParameterObj = object parameter
* 1 = premitive parameter
* ParameterDef = default parameter */
파라미터 앞에 ...
을 추가해서 표기
배열 형태로 전달됨
function number_list(...nums) {
//0부터 nums 리스트에 있는 내용의 갯수만큼 1씩 더해가며 대입하고 출력
for (i = 0; i < nums.length; i++) {
console.log(nums[i]);
}
}
number_list('one', 'two', 'three');
//for(const variable of iterable) {statement}
function print_list(...nums) {
for (const num of nums) {
console.log(num);
}
}
print_list("one", "two", "three");
function 안에 있는(local scope) 것과 바깥에 있는 것(global scope)
가장 중요한 규칙은
local scope에서는 local 과 global 모두 볼 수 있지만
global scope에서는 global것만 볼 수 있다.
같은 맥락으로
local scope내에서 child scope에 정의된 내용은 child scope에서만 보기가 가능하고 parent scope에서 보는 것이 불가능하다
마치 썬팅한 차의 창문과 같은 것!!!
let global = 'global';//global scope
function seeall() {
let msg = 'great';
console.log(msg);//local scope 이자 parent scope
function notseen() {
console.log(msg) // child scope에서 parent scope 확인 가능
let Anmsg = '!';
}
}
seeall();
return 따로 없으면 return undefined와 같음
function multiply(x, y) {
return x * y
}
const result = multiply(3, 5);
console.log(result);
const hi = function hi() {
console.log('hi');
};
hi();
//출력: hi
const hihi = hi;
hihi();
//출력: hi
variable 재정의하듯이 function도 가능함\
선언하기 전에 입력해도 hoist된다
자세한건 다음에...
도라방쓰
function 함수이름 (objparameter, callback할 함수1, callback할 함수2) { }
function insahae(insa, printhi, printbye) {
if (insa === "hi") {
printhi();
} else {
printbye();
}
}
const printhi = function () {
console.log("hi");
};// printhi() 선언
const printbye = function bye() {
console.log("bye");
}; // printbye() 선언
insahae("hi", printhi, printbye);// hi
insahae("molayo", printhi, printbye);// bye
항상 함수 이름은 따로 두지 않는다
const printwow = function() {
console.log('wow!');
};
printwow();
// wow!
const printwow = () => console.log('wow!');
//wow!
//함수가 한줄이 아닌 여러줄일 때 arrow function이용하기
const addandmultiplyb = (a, b) => {
let c = a + b;
return c * b;
};
console.log(addandmultiplyb(2, 3));
함수를 함수화시켜서 바로 호출하기??
function apple() {
console.log('Apple');
};
apple();
//Apple
이걸 IIFE화 시키면??
(function apple() {
console.log('Apple');})();
//Apple