객체의 key와 value의 값이 같다면 생략하여 작성할 수 있다.
{
const ellie1 = {
name: 'Ellie',
age: '18',
};
const name = 'Ellie';
const age = '18';
// 💩
const ellie2 = {
name: name,
age: age,
};
// ✨
const ellie3 = {
name,
age,
};
console.log(ellie1, ellie2, ellie3);
console.clear();
}
세가지 모두 같은 결과를 가진다.
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Object_initializer
객체의 키와 값에 접근하기 위해 .name 식으로 접근다면, 구조 분해 할당을 이용하면 객체 키 이름을 {}괄호 안에 정의해주고 = student라고 작성하면 스튜던트의 값들이 각각 name, level에 할당된다.
만약 다른 이름으로 선언하고싶을 때
새로운 이름을 작성하고 : 콜론을 이용해 원하는 이름을 선언한다.
배열에도 동일하게 사용가능하며 배열에 접근 하기위해 index를 이용한다.
물론 배열을 이용할때 [] 괄호를 사용한다.
// object
const student = {
name: 'Anna',
level: 1,
};
// 💩
{
const name = student.name;
const level = student.level;
console.log(name, level);
}
// ✨
{
const { name, level } = student;
console.log(name, level);
const { name: studentName, level: studentLevel } = student;
console.log(studentName, studentLevel);
}
// array
const animals = ['🐶', '😽'];
// 💩
{
const first = animals[0];
const second = animals[1];
console.log(first, second);
}
// ✨
{
const [first, second] = animals;
console.log(first, second);
}
console.clear();
}
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
새로운 배열을 만들고 배열 아이템을 하나하나 복사 할 때
spread를 이용하면 ...array
간단하게 배열을 복사할 수 있다.
즉 ...array
는 배열 아이템 하나하나 복사해 낱개로 가져오는 것을 말한다.
새로운 아이템 추가 할 때는 ...array syntax를 사용하고 추가하고싶은 아이템 작성한더.
객체는 레퍼런스만 복사되기 때문에 spread 오퍼레이터를 이용해 본래 값을 변경하면 모두 변경되니 주의한다.
객체도 {}을 이용해 복사가능하다.
배열 두개를 복사해서 가져와 병합하는 방법으로 두 개 이상의 배열을 합칠 수 있다.
병합할때 키가 동일한다면 가장 뒤에있는 키가 앞의 키를 덮어쓰니 주의한다.
{
const obj1 = { key: 'key1' };
const obj2 = { key: 'key2' };
const array = [obj1, obj2];
// array copy
const arrayCopy = [...array];
console.log(array, arrayCopy);
const arrayCopy2 = [...array, { key: 'key3' }];
obj1.key = 'newKey';
console.log(array, arrayCopy, arrayCopy2);
// object copy
const obj3 = { ...obj1 };
console.log(obj3);
// array concatenation
const fruits1 = ['🍑', '🍓'];
const fruits2 = ['🍌', '🥝'];
const fruits = [...fruits1, ...fruits2];
console.log(fruits);
// object merge
const dog1 = { dog: '🐕' };
const dog2 = { dog: '🐶' };
const dog = { ...dog1, ...dog2 };
console.log(dog);
console.clear();
}
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Spread_syntax
인자를 가진 함수를 정의한 뒤, 함수를 호출할 때 아무 인자도 호출하지않으면 undefined이 나온다. 이를 방지하기 위해 if문으로 디폴트메시지를 출력해야 하는데,디폴트 파라미터를 사용하면 인자다음에 기본적으로 원하는 초기값을 지정하여 설정된 디폴트값을 출력함으로 코드가 깔끔해진다.
{
// 💩
{
function printMessage(message) {
if (message == null) {
message = 'default message';
}
console.log(message);
}
printMessage('hello');
printMessage();
}
// ✨
{
function printMessage(message = 'default message') {
console.log(message);
}
printMessage('hello');
printMessage();
}
console.clear();
}
/**
* Ternary Operator
* https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
*/
{
const isCat = true;
// 💩
{
let component;
if (isCat) {
component = '😸';
} else {
component = '🐶';
}
console.log(component);
}
// ✨
{
const component = isCat ? '😸' : '🐶';
console.log(component);
console.log(isCat ? '😸' : '🐶');
}
console.clear();
}
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/Default_parameters
예시에서 isCat 변수가 true인지 false인지 따라 컴포넌트를 정리하고싶다면
if문으로 처리하는 경우가 많은데 Ternary Operator를 활용하면 코드를 간단하게 작성 할 수있다.
{
const isCat = true;
// 💩
{
let component;
if (isCat) {
component = '😸';
} else {
component = '🐶';
}
console.log(component);
}
// ✨
{
const component = isCat ? '😸' : '🐶';
console.log(component);
console.log(isCat ? '😸' : '🐶');
}
console.clear();
}
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
백틱, 달러사인, 괄호를 이용해 변수와 문자열을 간단하게 표현할 수 있다.
${}
{
const weather = '🌤';
const temparature = '16°C';
// 💩
console.log(
'Today weather is ' + weather + ' and temparature is ' + temparature + '.'
);
// ✨
console.log(`Today weather is ${weather} and temparature is ${temparature}.`);
}
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Template_literals
var의 변수스코프는 function단위,
const/let은 block 단위이다.
const는 상수, let는 변수를 선언할 때 사용된다.
변수를 선언할 때 var, let, const를 사용할 수 있는데 일반적으로 var는 선호되지 않는다. 이것은 var hoisting 라는 특성 때문이다.
호이스팅(Hoisting)이란, var 선언문이나 function 선언문 등을 해당 스코프의 가장 앞으로 끌어온 것처럼 동작하는 특성을 말한다.
function foo() {
let a = 1
if (true) {
let a = 2
console.log(a) // 2
}
console.log(a) // 1
}
prototype 기반의 대체재로 쓰임
클래스는 객체 지향 프로그래밍에서 특정 객체를 생성하기 위해 변수와 메소드를 정의하는 일종의 틀로, 객체를 정의하기 위한 상태(멤버 변수)와 메서드(함수)로 구성된다. 쉽게말해 다양한 오브젝트를 만들기 위한 청사진이라고 생각할 수 있다.
class Shape {
constructor() {}
}
class Rectangle extends Shape {
constructor(w, h) {
super(w, h)
this.w = 20
this.h = 10
}
getArea(w, h) {
return w * h
}
// get, set, static 예약어로 메서드를 설정할 수 있음
}
let rect = new Rectangle()
console.log(rect.getArea(30, 20)) // 600
// #1: 일반적인 화살표 함수
let square = (num) => {
return num * num
}
console.log(square(4)) // 16
// #2: 화살표 내의 this는 ES5의 function 내의 this와 다름
console.log(this === window) // true
let basket = {
_name: "ball",
_mates: ["rebound", "shoot", "pass"],
matesCount() {
console.log(this === window) // false
console.log(this) // basket 객체를 가리킴
this._mates.forEach(f => console.log(this._name + " is " + f ))
}
}
basket.matesCount()
// #3: 화살표 함수의 return 값
const even = [2, 4, 6, 8, 10, 12, 14]
const odd = even.map(n => n + 1)
const num = even.map((n, i) => n + i) // map(crruentValue, index, array)
console.log(even) // [2, 4, 6, 8, 10, 14]
console.log(odd) // [3, 5, 7, 9, 11, 13, 15]
console.log(num) // [2, 5, 8, 11, 14, 17, 20]
// #4: 비구조화 지원
const f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
console.log(f()) // 6