JavaScript / ES2024 / TC39

    Nowe funkcje JavaScript i TC39 Proposals

    ES2024 (Object.groupBy, Array.toSorted), Stage 3 (Decorators, Iterator Helpers), Temporal API i Pattern Matching — przyszłość JavaScript.

    groupBy
    Grupowanie
    toSorted()
    Immutable arr
    Iterators
    Lazy iter
    Temporal
    Date API

    6 propozycji JS — Stage i dostępność

    Object.groupBy, Array.toSorted, Decorators, Pattern Matching, Iterator Helpers i Temporal — Stage TC39, dostępność przeglądarek i zastosowanie.

    Propozycja Stage Dostępne Kiedy
    Object.groupBy() Stage 4 (ES2024) Chrome 117+, FF 119+, Safari 17.4+ Grupowanie danych bez reduce
    Array.toSorted/toReversed Stage 4 (ES2024) Chrome 110+, FF 115+, Safari 16+ Immutable array transforms
    Decorators Stage 3 Babel + TypeScript 5.0+ Class annotations, metadata
    Pattern Matching Stage 2 Babel plugin Strukturalne matchowanie wartosci
    Iterator Helpers Stage 3 Chrome 122+, Firefox 131+ Lazy iteration, brak array pośrednich
    Temporal API Stage 3 Polyfill (@js-temporal/polyfill) Bezpieczne daty, strefy czasowe

    Często zadawane pytania

    Nowe funkcje JavaScript ES2024 — co wchodzi do standardu?

    ES2024 (ECMAScript 2024) finalized: Object.groupBy() i Map.groupBy() — grupowanie. Array.prototype.toSorted(), toReversed(), toSpliced(), with() — immutable metody tablicy. Promise.withResolvers() — expose resolve/reject. ArrayBuffer.prototype.resize() i .transfer(). String.prototype.isWellFormed() i toWellFormed() — emoji poprawność. RegExp v flag — set operations. Object.groupBy: const grouped = Object.groupBy(users, user => user.department). Zamiast reduce. Nie mutuje. Czysty kod. Array immutable metody: const sorted = arr.toSorted() — brak mutacji (w odróżnieniu od sort()). const reversed = arr.toReversed(). arr.with(2, 'newValue') — zmień indeks niemutacyjnie. Stary sposób: [...arr].sort(). Nowy: arr.toSorted(). Promise.withResolvers: const {promise, resolve, reject} = Promise.withResolvers(). Zamiast new Promise((res, rej) => ...). Dobry dla manual control. Temporal API (Stage 3 TC39): nowe date/time API. Zastępuje Date. Temporal.PlainDate, PlainTime, ZonedDateTime. Bez problemów ze strefami czasowymi. Immutable. Parsowanie ISO 8601. Temporal.Now.zonedDateTimeISO(). Nie w ES2024 — nadal Stage 3. Polyfill: @js-temporal/polyfill. Używaj date-fns/luxon do produkcji.

    TC39 Stage 3 proposals — Pattern Matching, Decorators i Record/Tuple?

    TC39 Stages: 0-4. Stage 4 = w standardzie. Stage 3 = implementacja (kandydat). Stage 2 = szkic. Stage 1 = propozycja. Decorators (Stage 3): standaryzowane dekoratory. @sealed @enumerable class MyClass { @readonly name = 'test' }. Nie TypeScript decorators (legacy). Nowe: function sealed(cls, ctx) { Object.seal(cls.prototype) }. ctx.metadata, ctx.name, ctx.kind. class-methods: @logged method. @memoize method. TypeScript 5.0+: --experimentalDecorators lub nowe. Babel plugin: @babel/plugin-proposal-decorators (nowe). Pattern Matching (Stage 2): match expression. Jak switch ale potężniejszy. match (action) { when ({type: 'increment'}) => ({...state, count: state.count + 1}). when ({type: 'decrement'}) => ({...state, count: state.count - 1}). else => state }. Destructuring w warunkach. Guards: when (x) if (x > 0). Exhaustive matching. Records i Tuples (Stage 2): immutable value types. const record = #{name: 'Adam', age: 30}. const tuple = #[1, 2, 3]. Structural equality: #{a: 1} === #{a: 1} — true! Normalny object: {a: 1} === {a: 1} — false. Idealne dla CRDT, React state. Brak mutacji. Cloneable. Pipeline operator (Stage 2): x |> f |> g — jak pipe(). value |> double |> addOne |> console.log. Cleaner than f(g(h(x))). Dostępny przez Babel plugin. Import Attributes (Stage 3): import data from './data.json' with {type: 'json'}. import sheet from './style.css' with {type: 'css'}. Bezpieczeństwo importów.

    Array.groupBy, structuredClone i inne nowoczesne JS metody?

    Metody dostępne już w modernych przeglądarkach: structuredClone(obj): głęboka kopia. Nie JSON.parse(JSON.stringify()) — obsługuje Date, Map, Set, ArrayBuffer. structuredClone({date: new Date(), map: new Map()}). Nie kopiuje: functions, DOM nodes, WeakMap. Object.hasOwn(obj, 'key'): bezpieczne hasOwnProperty. Zastępuje obj.hasOwnProperty('key') lub Object.prototype.hasOwnProperty.call(obj, key). at() method: arr.at(-1) — ostatni element. str.at(-1) — ostatni znak. Zastępuje arr[arr.length - 1]. Array.from({length: n}, (_, i) => i): generuj tablice. findLast() i findLastIndex(): od końca. arr.findLast(x => x > 5). Bez arr.slice().reverse().find(). Error.cause: new Error('outer', {cause: err}). err.cause — oryginalny błąd. Stacktrace chain. String trimStart/trimEnd: str.trimStart(), str.trimEnd(). Szybsze niż regex. replaceAll: 'a.b.c'.replaceAll('.', '/'). Nie /./g. Object.entries/fromEntries: round-trip. Object.fromEntries(Object.entries(obj).filter(...)). Transformacja obiektów. queueMicrotask: queueMicrotask(() => {...}). Microtask queue. Przed macrotask (setTimeout). Lepsze niż Promise.resolve().then(). AbortController i AbortSignal: cancel fetch i async. const controller = new AbortController(). fetch(url, {signal: controller.signal}). controller.abort(). Używany przez React useEffect cleanup. WeakRef i FinalizationRegistry: słabe referencje. Cache bez wycieków. Registry callback przy GC. Zaawansowane — używaj rzadko.

    Nullish coalescing, optional chaining i inne ES2020-2022 features?

    ES2020 features: Nullish Coalescing (??): a ?? b — b tylko gdy a jest null/undefined. Nie false, 0, '' — to inaczej niż ||. const val = user.name ?? 'Anonymous'. Optional Chaining (?.): user?.address?.city — nie throw. arr?.[0] — bezpieczny index. fn?.() — call jeśli funkcja. Promise.allSettled([p1, p2]): nie rzuca gdy jedna odrzucona. [{status: 'fulfilled', value: ...}, {status: 'rejected', reason: ...}]. BigInt: 9007199254700000n. Wielkie liczby. Kryptografia. Blockchain. String.matchAll(): zwraca iterator. Wszystkie matchowania z grupami. ES2021 features: String.replaceAll(). Logical assignment: a ||= b (jeśli a falsy). a &&= b (jeśli a truthy). a ??= b (jeśli a null/undefined). WeakRef i FinalizationRegistry. Promise.any([p1, p2]): pierwszy sukces. Odwrotność Promise.all. Numeric separators: 1_000_000 = 1000000. Czytelność. ES2022 features: Top-level await: await fetch() w module bez async function. Object.hasOwn(). Error.cause. at() method. Array/String/TypedArray. class fields (private #name). Static class blocks: static { this.init() }. Class static fields. private methods. ES2023: Array.toSorted/toReversed/with/toSpliced. findLast/findLastIndex. Hashbang (#!). Change Array by copy.

    JavaScript Iterator Helpers i nowe propozycje — co nas czeka?

    Iterator Helpers (Stage 3): nowe metody na iteratorach. iter.map(fn), iter.filter(fn), iter.take(n), iter.drop(n). iter.flatMap(fn), iter.reduce(fn, init). iter.forEach(fn), iter.find(fn). Lazy evaluation — nie tworzy array pośrednich. [1,2,3,4,5].values().filter(x => x > 2).map(x => x * 2).take(2) — lazy. Brak Array.from w środku. Explicit Resource Management (Stage 3): using keyword. using resource = new Resource(). Automatyczne dispose() na końcu bloku. Jak C# using lub Python with. Symbol.dispose, Symbol.asyncDispose. TypeScript 5.2+: using keyword support. await using dla async. Set Methods (Stage 3): Set.prototype.union, intersection, difference, symmetricDifference, isSubsetOf, isSupersetOf, isDisjointFrom. Brak mapowania dwóch setów ręcznie. Temporal (Stage 3 — wkrótce): PlainDate, PlainTime, PlainDateTime. ZonedDateTime — strefa czasowa. Duration, Instant. Immutable. Globby — do produkcji gdy Stage 4. Float16Array (Stage 3): połowa precyzji float. AI/ML — mniejsze modele. WebGPU bufory. ArrayBuffer Float16. JSON.parse reviver (Stage 3): context param w reviver. Typ JSON. Ścieżka do klucza. Deferred Re-exports (Stage 2): export {default} from './heavy' deferred. Lazy export — nie wykonaj importu. Treeshaking hint. Import Assertions -> Import Attributes (Stage 3): with {type: 'json'}. Bezpieczeństwo typów importów. V8 i SpiderMonkey implementują.

    Czytaj dalej

    Powiązane artykuły

    Kontakt

    Skontaktuj się z nami

    Porozmawiajmy o Twoim projekcie. Bezpłatna wycena w ciągu 24 godzin.

    Wyślij zapytanie

    Bezpłatna wycena w 24h
    Bez zobowiązań
    Indywidualne podejście
    Ekspresowa realizacja

    Telefon

    +48 790 814 814

    Pon-Pt: 9:00 - 18:00

    Email

    adam@fotz.pl

    Odpowiadamy w ciągu 24h

    Adres

    Plac Wolności 16

    61-739 Poznań

    Godziny pracy

    Pon - Pt9:00 - 18:00
    Sob - NdzZamknięte

    Wolisz porozmawiać?

    Zadzwoń teraz i porozmawiaj z naszym specjalistą o Twoim projekcie.

    Zadzwoń teraz