1. let과 const
- let변수는 중복선언이 불가능하다.
- let변수의 유효범위는 {}블록이다.
let y = 1;
let z = 10;
if(true) {
let z = 100;
console.log(z);
}
console.log(z);
1. const
const GENDER = "남자";
const arr = ["홍길동", "이순신", "홍길자"];
arr[0] = "김철수";
arr.push("박영희");
const P1 = {"name" : "홍길동" };
P1.name = "이순신";
P1.age = 20;
2. spread operator (전개구문)
- 반복 가능한(iterable)에 적용할 수 있는 문법입니다.
- 배열이나 문자열 등을 아래처럼 풀어서 요소 하나 하나로 전개시킬 수 있습니다.
const arr = [1,2,3];
console.log(...arr);
const str1 = 'hello';
const str2 = [...str1];
console.log(str2);
const num1 = [10, 20, 30, ...arr];
console.log(num1)
const num2 = [10, 20, ...arr, 30];
console.log(num2)
const num3 = [...arr];
console.log(num3)
const num4 = [...arr, ...arr]
console.log(num4)
3. 함수에서 spread operator
const num = [1,2,3];
function sum(x, y, z) {
return x + y + z;
}
console.log( sum(...num) );
console.log( sum(10, ...num) );
function sum2(x, ...arr) {
return [x, ...arr];
}
console.log( sum2("홍길동", 1) )
console.log( sum2("홍길동", 1,2) )
console.log( sum2("홍길동", 1,2,3) )
function sum3(x, y = 10, z = 100) {
return x + y + z;
}
console.log( sum3(1) )
console.log( sum3(1, 2) )
console.log( sum3(1, 2, 3) )
console.log( sum3(...[1,2] ))
3. Destructuring assignment (구조 분해 할당)
1. 배열에서 destructuring
let arr = ["홍길동", "이순신", "홍길자", "김철수"];
let [a,b,c,d] = arr;
console.log(a,b,c,d)
let [n1, , ,n2] = arr;
console.log(n1, n2)
let [...x] = arr;
console.log(x);
let [k1, k2, ...all] = arr;
console.log(k1, k2, all)
2. 객체에서 destructuring
let person = {
"name": "김철수",
"age" : 30,
"job" : ["programmer", "designer"]
}
let {name} = person;
console.log(name);
let {name, age, job} = person;
console.log(name, age, job);
let {name: aaa, age:bbb} = person;
console.log(aaa, bbb)
4. for of문
1. 반복 가능한 객체(iterable)를 for문 안에서 반복시켜 연속된 결과값을 얻습니다.
2. forEach문에서 지원하지 않는 break, continue, return의 사용가능
let arr = ["a", "b", "c"];
for(let i of arr ) {
console.log(i);
}
let obj = {name: "g", age: 1};
for(let i of obj) {
console.log(i);
}
5. Backtick
1. 백틱 `을 용해서 문자열을 표현하고, 템플릿 리터럴 ${}를 이용해서 필요값을 처리
let name = '홍길동';
let age = 20;
console.log('제 이름은 ' + name + '이고 나이는 ' + age + "입니다");
console.log(`제 이름은 ${name}이고 나이는 ${age}입니다`);
6. Arrow Function (화살표함수 👍)
1. 화살표 함수는 기본적으로 익명함수를 대체합니다. (호이스팅 불가)
2. 가독성이 향상됩니다.
let a = () => {
console.log('a실행');
}
문법1
코드가 한개줄이면 {} 생략이 가능하다
{}를 쓰지 않으면 기본값으로 undefined를 반환합니다.
{}를 쓰지 않고 구문을 작성하면 리턴문이 됩니다.
let b1 = (a) => console.log(a);
console.log( b1(1) );
let b3 = (a, b) => a + b;
console.log( b3(1, 2) );
문법2
매개변수가 1개라면, 매개변수 자리의 ()의 생략이 가능합니다.
let func = a => a + 10;
console.log ( func(10) );
문법3
객체를 반환 할때는 ()를 묶어 줍니다.
let c = () => {
return {key: '홍길동'};
}
let d = () => ({key: '이순신'});
화살표 함수의 응용 forEach, filter, map
1. forEach - 반복문
array.forEach(callbackFunction(currenValue, index, array), thisArg)
- currenValue: 현재값
- index: 현재인덱스
- arrayt: 현재배열,
- thisArg: callbackFunction 내에서 this로 사용될 값
list.forEach( function(x, y, z) {
console.log(x, y, z);
});
list.forEach( (x,y,z) => console.log(x,y,z) )
2. filter - 요소개수만큼 반복하며 boolean을 이용한 새로운 list를 만듬
array.filter(callbackFunction(currenValue, index, array), thisArg)
var result = list.filter( function(x, y, z) {
return x % 2 == 0;
});
console.log(`result: ${result}`);
var result = list.filter( (x, y, z) => x % 2 == 0);
3. map - 실행한 결과를 가지고 새로운 배열을 만들 때 사용
array.map(callbackFunction(currenValue, index, array), thisArg)
var result2 = list.map( function(x, y, z) {
return x * x;
});
console.log(`result2: ${result2}`);
var result2 = list.map( x => x * x );
4. this키워드의 사용 - 일반함수로만 가능
let result3 = list.map(function(x) {
return x % this.value == 0 ? true : false;
}, {value: 5});
console.log(result3);
7. class
일반HTML에서는 굳이 class를 사용하진 않습니다.
React의 class컴포넌트를 사용한다면 알아두세요.
1. 클래스의 멤버변수를 선언할 때는 키워드를 사용하지 않습니다. (구형브라우저에서는 지원불가 할 수 있음)
class Person {
name = '홍길동';
age = 20;
state = {
a: 1,
b: () => {
return 'obj의 b';
}
}
constructor(addr) {
this.addr = addr;
}
func = (a) => {
return "함수호출";
}
}
let p = new Person();
console.log(p.name)
console.log(p.age)
console.log(p.func());
console.log(p.state.a);
console.log(p.state.b());
let p2 = new Person('서울시');
console.log(p2.addr);
클래스 상속
class Shape {
constructor() {}
}
class Rect extends Shape {
constructor(w, h) {
super();
this.w = 20;
this.h = 10;
}
setW(w) {
this.w = w;
}
setH(h) {
this.h = h;
}
getArea() {
return this.w * this.h
}
}
let rect = new Rect();
console.log(rect.getArea())
rect.setH(100);
rect.setW(20);
console.log(rect.getArea())
8. module import export
* 모듈 임포트
- 모듈은 JS ES6문법에서 미리 작성해 놓은 스크립트 파일이며, 모듈 안에는 변수, 함수, 클래스 등이 정의되어 있습니다.
- ES6부터는 주요기능들을 모듈로 구성하여 사용이 가능합니다.
- 모듈을 내보내는 방법은 named export방식과 default export방식 2개가 있습니다.
- 여러 값을 내보낼 때 named export방식
- 단일 값을 내보낼 때 default export방식
script01.js
export const name = '홍길동';
export const age = 20;
export const getInfo = () => {
console.log('이름:', name, '나이:', age);
}
let sum = 0;
let add = (x) => {
sum += x;
console.log(sum);
}
export {sum, add};
script01.html
- HTML5파일에서 예외적으로 module을 사용할려면 type="module" 문을 반드시 작성합니다.
<script type="module">
import {name, age, getInfo} from './script01.js';
console.log(name);
console.log(age);
getInfo();
import * as test from './script01.js';
console.log(test.name);
console.log(test.age);
test.getInfo();
console.log(test.sum);
test.add(10);
import {name as n, age as a, getInfo as get} from './script01.js';
console.log(n);
console.log(a);
get();
</script>
하나의 모듈에서 하나의 객체를 이름으로 내보낼 때 단일 객체 내보내기 export default문을 사용합니다.
Class나 함수를 내보낼떄는 세미콜론을 붙이지 않도록 권유됩니다.
script02.js
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
getInfo = () => {
return '이름:' + this.name;
}
}
export default Person
script02.html
<script type="module">
import Person from './script03.js';
let park = new Person('홍', 20);
console.log(park.name);
console.log(park.age);
</script>