Front/JavaScript

Front/JavaScript

[JavaScript] Promise

A promise is an object that may produce a single value sometime in the future.It is either a resolved value or a rejected one, with a reason for rejection.And a promise may be in one of three possible states.It can be fulfilled, rejected, or pending. [1] new Promiseconst promise = new Promise((resolve, reject) => { setTimeout(() => { resolve("success"); }, 4000)});promise.then(console.log..

Front/JavaScript

[JavaScript] findLast, toSorted, toReversed, toSpliced, with (ES2023)

1. findLast / findLastIndexfind() 는 앞에서부터 조건을 만족하는 첫 요소를 찾고,findLast() 는 뒤에서부터 찾는다. const numbers = [1, 2, 3, 4, 5, 6];console.log(numbers.find(n => n % 2 === 0)); // 2console.log(numbers.findLast(n => n % 2 === 0)); // 6console.log(numbers.findLastIndex(n => n % 2 === 0)); // 5  2. toSorted / toReversed / toSpliced / with원본 배열은 변경하지 않고, 새로운 배열을 반환한다.React 같이 불변성 유지가 중요한 프레임워크에서 유용히..

Front/JavaScript

[JavaScript] replaceAll (ES2021), at (ES2022)

1. replaceAllreplace 는 첫번째 키워드만 바꿀 수 있지만replaceAll 은 문자열의 모든 키워드를 바꿀 수 있다.const str = "You are the best of the best";const str_1 = str.replaceAll('best', 'worst');// "You are the worst of the worst"const str_2 = str.replace('best', 'worst');// "You are the worst of the best"  문자열은 불변(immutable) 타입이기 떄문에 문자열 자체를 바꿀 수 없다.대신, replace() 같은 메서드로 원본을 직접 수정하지 않고, 새로운 문자열을 반환해 사용한다.이때, let 으로 선언한 문자열은 재..

Front/JavaScript

[JavaScript] ES20 - '?.' 와 '??'

1. Optional Chaining: ?. : 값이 있을 수도 있고 없을 수도 있는 상황에서 주로 사용한다. 중첩 객체의 특정 속성에 접근하기 위해서 기존에는 일일이 And 로 연결해 속성의 존재 여부를 확인해야 했다.하지만 이렇게 되면 코드가 너무 길어지고, 조건문 속 속성이 없을 경우 TypeError 에러가 뜰 수 있다. 옵셔널 체이닝 (A ?. B) 은 A가 undefined 나 null 이면 바로 undefined 를 반환하고 에러 없이 멈춘다. 또한, 코드가 간결하고 읽기 쉬우며null 체크를 매번 하지 않아도 돼서 실수가 줄어든다. let will_pokemon = { pikachu: { friend: { charizard: { ..

Front/JavaScript

[JavaScript] array (2) - map

0. map 이란: 기존 배열을 변형(각 요소를 가공)해서 새로운 배열을 반환한다.: 기존 배열은 변경되지 않는다. (불변성 유지): 콜백 함수를 인자로 받고, 원본 배열의 각 요소를 순회하면서 변형된 값을 새 배열에 저장한다.- 숫자 변환, 데이터 매핑 등, 배열의 각 요소를 변형해야 하는 경우 유용하다. ※ reduce() 는 배열을 순회하며 하나의 최종 값을 반환할 때 쓰인다. (합계, 평균, 객체 변환 등)※ forEach() 는 배열을 단순히 순회하고 작업을 수행할 뿐, 반환값은 없다. const newArray = oldArray.map((element, index, array) => { return 변환된_값;});element - 현재 배열 요소index - 현재 요소의 인덱스 (선택사항..

Front/JavaScript

[JavaScript] ES10 - flat/flatMap, Object.fromEntries, trimStart/trimEnd

1. flat / flatMapArray.prototype.flat(n): 중첩된 배열을 펼쳐서 1차원 배열로 만든다. - n이 빈값이면 기본적으로 1단계만 펼침- n단계까지 펼치고,- 특정 숫자를 지정하기 어려울 때 Intinity 를 넣으면 배열의 depth 와 관계없이 1차원 배열로 만든다.const array = [[1],[2],[3],[[[4]]],[[[5]]]]console.log(array.flat(2)) // [1,2,3,[4],[5]]const trapped = [[[[[[[[[[[[[[[[[[[[[[[[[[3]]]]]]]]]]]]]]]]]]]]]]]]]];console.log(trapped.flat(Infinity)) // [3] Array.prototype.flatMap(): map..

Front/JavaScript

[JavaScript] 반복문 -- for-of / for-in (Iterating vs. Enumerating)

const basket = ['apples', 'oranges', 'grapes']// forfor ( let i = 0; i { console.log(item);}// whilelet i = 0;while (i   자바스크립트에는 크게 기본 반복문(Traditional Loops)와 고급 반복문 (Modern Loops) 이 있다.기본 반복문은 인덱스 기반으로 배열이나 숫자 범위를 반복할 때 사용되며,for 문, while 문, do...while문 이 있다.고급 반복문은 기본 반복문보다 더 직관적이고 선언적인 방식으로 사용되며,forEach, for...of, for...in 이 있다. 그 중에서 가장 헷갈리는 for...of 와 for...in 에 대해 이해하는 시간을 가져보자.  1. for....

Front/JavaScript

[JavaScript] array (1) - reduce

0. reduce 란?array.reduce((accumulator, currentValue) => { // 콜백 함수 내용}, initialValue); reduce() 는 배열의 모든 요소를 하나로 축소하는 데 사용하는 메서드이다.배열을 합치거나, 필터링하거나, 특정 조건을 만족하는 값을 찾을 때 유용하다. accumulator (누적값): 배열의 요소들을 하나씩 처리하면서 누적되는 값. 처음에는 initialValue로 시작해.currentValue (현재값): 배열에서 순차적으로 처리되는 각 요소.initialValue(초기값): 누적값이 시작하는 초기값 (옵션, 생략 가능).결과값: 배열을 모두 처리한 후 최종적으로 하나의 값이 반환됨. 첫번째 요소부터 마지막 요소까지 차례대로 순회하며 acc..

함s
'Front/JavaScript' 카테고리의 글 목록