본문 바로가기

반응형

ES6

(17)
Default Values es6에서 function에 추가된 것. Default Values. 기본 값은 많은 사람들이 필요로 했던 것. 왜냐면 시간을 줄여주기 때문. 기본 값은 arrow function뿐만 아니라, 일반함수에 적용 가능. See the Pen 200917-1 by hwd3004 (@hwd3004) on CodePen. Hello aaa가 출력. 여기까지는 이상 없음. 그런데 유저가 자기 이름을 입력 안하면? See the Pen 200917-2 by hwd3004 (@hwd3004) on CodePen. Hello undefined가 뜸. return 'Hello ' + (aName || ' anon'); 을 하는 방법이 있지만 default value를 이용한 방법이 있음. See the Pen 200917..
forEach(), map() 각 array의 엘리먼트마다 제공된 함수를 실행 메일 주소에서 @과 그 뒤에 있는 것들은 없애고 싶을 때 See the Pen temp04 by hwd3004 (@hwd3004) on CodePen. @ 뒤에꺼 필요없으면 See the Pen temp05 by hwd3004 (@hwd3004) on CodePen. See the Pen temp06 by hwd3004 (@hwd3004) on CodePen. map은 forEach지만 반환된 엘리멘트들로 새로운 array를 만듬 implicit return 으로 코드 한줄로 가능 See the Pen temp07 by hwd3004 (@hwd3004) on CodePen. 객체로 하고 싶을때
filter() - includes() filter 메소드는 제공된 함수의 조건을 만족한 모든 엘리먼트로 새로운 array를 만듬. See the Pen temp03 by hwd3004 (@hwd3004) on CodePen. gmail을 제외한 나머지 메일들을 배열로 반환
find() - includes() item.includes() 제공되는 테스트 조건을 만족하는 첫번째 엘레먼트 값을 리턴하는 함수 See the Pen temp01 by hwd3004 (@hwd3004) on CodePen. 콘솔창을 확인해보면 "aaa@naver.com" 확인 가능 See the Pen temp02 by hwd3004 (@hwd3004) on CodePen. item.includes() 를 써서 gmail을 찾아봄. includes 는 string을 찾아줌 콘솔창을 확인해보면 "bbb@gmail.com" 확인 가능
arrow function을 사용하지 않아야할 때. 'this' aaa const button = document.querySelector('button') button.addEventListener('click', function(){ console.log(this) this.style.backgroundColor = "red"; }) this가 버튼을 가르키지만, 애로우 펑션으로 바꾸면 this는 window를 가르키게 된다.
arrow function 애로우 펑션은 자바스크립트에서 함수의 모습을 개선한 것이다. var처럼 let과 const로 대체되는 것은 아니고, 그냥 좀 더 보기 좋게 만든 것이다. aaa, bbb, ccc, ddd 를 aaa123, bbb123, ccc123, ddd123 으로 바꾸는 코드 2개. const name = ["aaa", "bbb", "ccc", "ddd"] const temp = name.map(function(item){ return item + "123" }) console.log(temp) 또는 const name = ["aaa", "bbb", "ccc", "ddd"] function temp(item){ return item + "123" } const temp2 = name.map(temp) console...
block scope let과 const의 또 다른 장점은 block scope가 있다는 점이다. 스코프는 기본적으로 버블이다. 이 버블이 variable들이 접근가능한지 아닌지를 감지한다. if (true) { const hello = "hi"; } console.log(hello); 이런 코드가 있을때, const이든 let이든 에러가 안뜰리 없다. block은 {} 이걸로 만들어져있다. {} 밖에서 hello는 존재하지 않는 것이다. 그런데 if (true) { var hello = "hi"; } console.log(hello); 코드를 실행해보면 hi가 콘솔창에 출력된다. if, while, for 구문안에서 var로 변수를 만들 수 있다. var는 block scope를 사용하지않고, function scope를 ..
dead zone temporal dead zone은 let이랑 같이 소개되는 개념이다. var name = 'aaa' console.log(name) 를 하면 콘솔창에 당연히 aaa가 뜬다. console.log(name) var name = 'aaa' 그런데 둘의 자리를 바꾸면 undefined가 뜬다. 자바스크립트는 위에서부터 아래로 코드를 실행하기때문에, 이론상으론 존재하지 않는걸 콘솔로그로 출력하려한것이다. console.log(name) 다른 것 없이 이것만 하면 에러가 난다. 에러가 나는 이유는 자바스크립트가 호이스팅이란걸 해주기 때문이다. var name console.log(name) name = 'aaa' undefined가 뜬다. 실제로는 에러가 떠야한다. 어플리케이션을 만들때 undefined가 뜬걸..

반응형