함수
function(){ }
//또는
() =>{ }
함수에 이름 붙이기
function a() { } 함수 선언문(세미콜론 없음)-오래된 관습
const b = function() { }; 함수 표현식
const c = ( ) => { }; 화살표 함수
return은 함수를 종료 시킨다.
function c() {
return 'hello';
console.log('h1');
}
c()
<실행결과>
hello
h1는 출력이 안된다.(함수가 이미 종료 되었으므로)
함수에 return문이 없는 경우
"return undefined"가 생략된 것이다.
배열로 리턴하기
function a(){
return [1, 5]
}
parameter와 argument
function a(paremeter){
}
a(argument)
parameter에 argument를 넣는다.
함수는 여러개의 매개 변수를 갖을 수 있고,
매개변수와 인수의 개수가 일치하지 않아도 된다.
인수보다 매개변수가 많은 경우
function a(w, x, y, z){
console.log(w, x, y)
}
a('Hello', 'Parameter', 'Argument')
<실행결과>
Hello Parameter Argument undefined
인수보다 매개변수가 적은 경우
function a(w, x){
console.log(w, x)
}
a('Hello', 'Parameter', 'Argument')
<실행결과>
Hello Parameter
화살표 함수의 특징
const f =(x,y,z) => {
return x * y * z;
}
const f= (x, y, z) => x*y*z;
x,y,z => x*y*z;
객체 리터럴
const name ='조현영';
const year = 1994;
const month = 8
const date = 12;
const gender = 'M';
const zercho = {
name ='조현영',
year = 1994,
month = 8,
date = 12,
gender = 'M',
};
속성 이름은 문자열 이어야 하고, 속성 값은 자바스크립트의 모든 값이 될수 있다.
객체 변수를 통해 객체의 속성에 접근할 수 있다.
const zercho = {
name ='조현영',
year = 1994,
month = 8,
date = 12,
gender = 'M',
};
console.log(zerocho.name);
console.log(zerocho['name']);
console.log(zerocho.date);
console.log(zerocho['date']);
const obj = {
bc: 'hello'
'2ca': 'hello',
'c a': 'hello',
'c-a': 'hello',
}
속성에 숫자, 띄어쓰기, 특수문자 등 이 존재하는 경우에는 ''로 감싸준다.
console.log(obj.bc);
console.log(obj['bc']);
console.log(obj.2bc) //error
console.log(obj['2bc']); //OK
객체 속성 수정하기(객체 내부는 수정이 가능하다)
zerocho.gender = 'F';
객체 속성 제거하기
delete zerocho.gender;
메서드 : 객체의 속성 값으로 함수를 넣었을 때 이 속성을 특별히 메서드(method)라고 한다.
const debug = {
log: function(value){ console.log(value); },
속성: 값
};
debug.log('Hello, Method');
객체이름.속성이름(매개변수)
debug객체 안에 log메서드가 있다고 말한다.
객체간의 비교
{ } === { }
객체끼리 비교하는 경우 false
why? 좌측에 새로운 객체, 우측에 새로운 객체 둘 다 새로운 객체이므로 서로 다르다. 따라서 false
참고, 객체가 아닌 숫자, 문자열, 불 값, null, undefined는 모두 true를 반환합니다.
'str' === 'str';
123 === 123;
false === false;
null === null;
undefined === undefined
결론 같은 객체인지 비교하고 싶다면 기존 객체를 변수에 저장 후 비교해야 합니다.
const a = { name: 'zerocho' };
const array = [1, 2, a];
console.log(a === array[2]);
<실행결과>
true
원시형과 참조형(훈훈한 자바스크립트 참조)
const array = [1, 2, 3];
console.log(array === [1, 2, 3];)
<실행결과>
false
why? 두번째 줄 우측에 [1, 2, 3]은 새로운 객체가 생성된 것이므로
2번째 줄에서 array와 [1, 2, 3]은 다르다.
쿼즈: '조'에 접근하는 방법은??
const zerocho = {
name: {
first: '헌영',
last: '조',
},
gender: 'm';
};
zerocho.name.last;
객체이름 객체이름
zerocho['name']['last']