Basic JavaScript
let 이나 const 키워드 없이 생성된 변수는 자동적으로 글로벌 스코프에 생성된다. 함수나 블럭 안에 정의할지라도 어디서나 접근 가능
>, >=, <, <=, == 로 비교 연산 시 비교 가능한 형태로 자동 형변환이 일어난다. ex. 5 > '3' (true)min <= N <= max 인 정수 난수 생성: Math.floor(Math.random() * (max - min + 1)) + min
obj.hasOwnProperty(prop) : prop 같은 이름의 프로퍼티가 존재하는지 true, false 반환
ES6
const 변수에 array 할당 시 새로운 array(공간) 할당은 불가능하지만 각 element는 변경 가능하다. ex) arr[n] = m;
var는 어디서 선언하든 글로벌 변수처럼 작동하고 같은 이름의 변수를 선언하는 것도 가능 (혼란을 야기하니 사용하지 말자)
strict 하게 데이터의 변경 방지: Object.freeze(obj)
obj.PI 에 대한 변경 시도 -> TypeError
TypeError: Cannot assign to read only property 'PI' of object '#<Object>'
Anonymous Function
const myFunc = function() {
const myVar = "value";
return myVar;
}
-> arrow function syntax (ES6)
const myFunc = () => {
const myVar = "value";
return myVar;
}
-> 함수 body가 없고 return 값만 있는 경우
const myFunc = () => "value";
const multiplier = (item, multi) => item * multi;
multiplier(4, 2);
Default Parameters
const greeting = (name = "Anonymous") => "Hello " + name;
console.log(greeting("John")); //Hello John
console.log(greeting()); //Hello Anonymous
Rest Parameter
...args: 넘어온 arguments 를 array로 반환한다. map(), filter(), reduce() 사용 가능
const sum = (...args) => {
return args.reduce((a, b) => a + b, 0); //args elements의 합
}
Spread Operator
배열 복사
const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];
const arr2 = [...arr1];
console.log(arr2); //['JAN', 'FEB', 'MAR', 'APR', 'MAY']
배열 병합
var arr1 = [1,2,3];
var arr2 = [4,5,6];
var arr = arr1.concat(arr2);
console.log(arr); // [ 1, 2, 3, 4, 5, 6 ]
// ES6 spread operator
var arr = [...arr1, ...arr2];
arr1.push(...arr2)
Math.max() 적용
var arr = [6, 89, 3, 45];
var maximus = Math.max.apply(null, arr); //Math.max(arr) returns NaN
const maximus = Math.max(...arr);
Destructuring Assignment
구조 분해 할당
Object
const HIGH_TEMPERATURES = {
yesterday: 75,
today: 77,
tomorrow: 80
};
//const today = HIGH_TEMPERATURES.today;
//const tomorrow = HIGH_TEMPERATURES.tomorrow;
const { today, tomorrow } = HIGH_TEMPERATURES;
const { today:highToday, tomorrow:highTomorrow } = HIGH_TEMPERATURES; //새로운 이름의 변수에 할당
console.log(highToday, highTomorrow);
const LOCAL_FORECAST = {
yesterday: { low: 61, high: 75 },
today: { low: 64, high: 77 },
tomorrow: { low: 68, high: 80 }
};
// const lowToday = LOCAL_FORECAST.today.low;
// const highToday = LOCAL_FORECAST.today.high;
const { today: { low: lowToday, high: highToday }} = LOCAL_FORECAST;
console.log(lowToday, highToday); //64 77
Array
let a = 8, b = 6;
[a, b] = [b, a];
console.log(a, b); //6 8
Array.prototype.slice() 와 비슷한 동작
const [a, b, ...arr] = [1, 2, 3, 4, 5, 7];
console.log(a, b); // 1 2
console.log(arr); // [3, 4, 5, 7]
function removeFirstTwo(list) { // 첫 번째와 두 번째 요소를 제외한 array 반환
const [a, b, ...shorterList] = list;
return shorterList;
}
const source = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const sourceWithoutFirstTwo = removeFirstTwo(source); // [3, 4, 5, 6, 7, 8, 9, 10]
Object Properties -> Function Parameters
const profileUpdate = (profileData) => {
const { name, age, nationality, location } = profileData;
}
const profileUpdate = ({ name, age, nationality, location }) => {
}
Template Literals
`Hello, my name is ${person.name}! I am ${person.age} years old.`
Object Property Shorthand
const createPerson = (name, age, gender) => {
return {
name: name,
age: age,
gender: gender
};
};
const createPerson = (name, age, gender) => ({name, age, gender});
Object 안에 프로퍼티 함수 정의시 function 키워드 생략 가능
함수명(){ ... }
const person = {
name: "Taylor",
sayHello: function() {
return `Hello! My name is ${this.name}.`;
}
};
const person = {
name: "Taylor",
sayHello() {
return `Hello! My name is ${this.name}.`;
}
};
클래스 생성자 ( constructor() )
new 연산자로 객체 생성시 호출
class Vegetable {
constructor(name) {
this.name = name;
}
}
Getter / Setter
함수 이름: get xxx(), set xxx(value) -> obj.xxx 로 호출한다.
class Book {
constructor(author) {
this._author = author;
}
get writer() {
return this._author;
}
set writer(updatedAuthor) {
this._author = updatedAuthor;
}
}
const novel = new Book('anonymous');
console.log(novel.writer); //anonymous
novel.writer = 'newAuthor';
console.log(novel.writer); //newAuthor
Module Script
html 파일에 자바스크립트 코드(파일) 가져오기
<script type="module" src="filename.js"></script>
Import / Export
export myFunc(){ ... }
import { myFunc } from './myFile.js';
import * as everything from './myFile.js'; //파일 내 모든 성분을 가져옴 (everything.xxx 로 접근)
export defualt myFunc(){ ... } : fallback 선언. 파일이나 모듈에서 하나만 내보낼 때 사용
import myFunc from './myFile.js'; : {} 없이 import 가능
Promise 클래스: 비동기 처리
주로 서버에서 받아온 데이터를 화면에 표시할 때 사용
Promise의 state
- 대기(pending): 이행하지도, 거부하지도 않은 초기 상태. new Promise() 호출한 상태
- 이행(fulfilled): 연산이 성공적으로 완료됨
- 거부(rejected): 연산이 실패함
resolve: 연산(응답)이 성공하면 호출되는 콜백 메서드 -> fulfilled 상태
reject: 연산(응답)이 실패하면 호출되는 콜백 메서드 -> rejected 상태
const myPromise = new Promise((resolve, reject) => {
});
fulfilled 상태가 되면 처리 결과 값을 then 메서드를 통해 받아올 수 있다.
rejected 상태가 되면 실패한 이유(실패 처리의 결과 값)를 catch()로 받아올 수 있다.
const makeServerRequest = new Promise((resolve, reject) => {
// responseFromServer is set to true to represent a successful response from a server
// responseFromServer is set to false to represent an unsuccessful response from a server
let responseFromServer;
if(responseFromServer) {
resolve("We got the data");
} else {
reject("Data not received");
}
});
makeServerRequest.then(result => {
console.log(result); // We got the data
});
makeServerRequest.catch(error => {
console.log(error); // Data not received
});
Regular Expressions
Test(): 정규식 테스트
정규식은 문자열이 아니다. "", '' 사용하지 않음
정규식.test( 문자열 ) => true 또는 false 반환
let testStr = "freeCodeCamp";
let testRegex = /Code/;
testRegex.test(testStr); // true
'Advance II > JavaScript' 카테고리의 다른 글
| [JS] call, apply, bind (0) | 2023.09.18 |
|---|