Upgrade to Pro — share decks privately, control downloads, hide ads and more …

var, let, const and immutable of JavaScript

Araya
August 20, 2018

var, let, const and immutable of JavaScript

JavaScriptのvar, let, constによる変数宣言、immutableについて、社内LTで話しました。

Araya

August 20, 2018
Tweet

More Decks by Araya

Other Decks in Programming

Transcript

  1. ઌͣconstΑΓ࢝ΊΑ @arayaryoma 2018/08/20 - ϔϚλΠτࣾ಺LT

  2. ٱʑʹJavaScriptॻ͚͘ͲES2015ͱ͔ ͍͏΍ͭͰ͍Ζ͍ΖมΘͬͯΔͬΆ͍ʁ ม਺એݴ࣌ɺvar ͚ͩ͡Όͳͯ͘let΋࢖͑Δʁ var͸ม਺ͩ͠let͸ఆ਺ͬΆ͍…ʁ Μɺconst΋͋Δʁ ΋͔ͯ͠͠ࢲͷJavaScriptɺ3೥஗ΕͯΔʁ

  3. ٱʑʹJavaScriptॻ͚͘ͲES2015ͱ͔ ͍͏΍ͭͰ͍Ζ͍ΖมΘͬͯΔͬΆ͍ʁ ม਺એݴ࣌ɺvar ͚ͩ͡Όͳͯ͘let΋࢖͑Δʁ var͸ม਺ͩ͠let͸ఆ਺ͬΆ͍…ʁ Μɺconst΋͋Δʁ ΋͔ͯ͠͠ࢲͷJavaScriptɺ3೥஗ΕͯΔʁ ࠓ೔͸ͦΜͳ͋ͳͨͷͨΊʹ
 varͱletͱconstͷҧ͍Λ ղઆ͠·͢

  4. ٱʑʹJavaScriptॻ͚͘ͲES2015ͱ͔ ͍͏΍ͭͰ͍Ζ͍ΖมΘͬͯΔͬΆ͍ʁ ม਺એݴ࣌ɺvar ͚ͩ͡Όͳͯ͘let΋࢖͑Δʁ var͸ม਺ͩ͠let͸ఆ਺ͬΆ͍…ʁ Μɺconst΋͋Δʁ ΋͔ͯ͠͠ࢲͷJavaScriptɺ3೥஗ΕͯΔʁ ͜ͷεϥΠυΛݟऴΘΔࠒ ͋ͳͨ͸varΛॻ͔ͳ͍਎ମʹ ͳ͍ͬͯΔͰ͠ΐ͏

  5. ࿩͢͜ͱͱ݁࿦ JSͷvar, let, constͷҧ͍ͱ࢖͍ॴ ϞμϯͳJSͷॻ͖ํ(ྲྀߦ)ʹ͍ͭͯগ͚ͩ͠ var͸׬શʹෆཁ ·ͣ͸constͰॻ͘

  6. redeclaration(࠶એݴ)

  7. var let const

  8. ಈ͘ʁ

  9. ಈ͘(variable shadowing)

  10. const΋ಉ͡ ಈ͕͘Մಡੑ͕Լ͕ΔͷͰආ͚Δ΂͖

  11. scope(ม਺είʔϓ)

  12. varͰએݴͨ͠ม਺ͷείʔϓ͸function಺ (τοϓϨϕϧʹએݴͨ͠৔߹͸άϩʔόϧ)

  13. if(){}ͳͲͷϒϩοΫ಺Ͱએݴͨ͠ม਺Λ ϒϩοΫͷ֎͔ΒࢀরͰ͖Δ

  14. letͰએݴͨ͠ม਺͸είʔϓ͕ϒϩοΫ಺

  15. const΋ಉ͘͡ϒϩοΫείʔϓ

  16. switch-caseͷ᠘

  17. blockʹͯ͠ղܾ

  18. reassign(࠶୅ೖ)

  19. var͸࠶୅ೖՄೳ

  20. let΋࠶୅ೖՄೳ

  21. const͸࠶୅ೖෆՄೳ

  22. ͨͩ͠constͰએݴͯ͠΋immutableͰ͸ͳ͍ͷͰ஫ҙɻ Objectͷproperty΍Arrayͷཁૉ͸͍͘ΒͰ΋ॻ͖׵ΘΔɻ

  23. var let const ࠶એݴ είʔϓ function block block ࠶୅ೖ immutable?


    (primitiveͳσʔλܕҎ֎) NO NO NO
  24. ࣮ફྫͰݟΔ
 ݱ୅෩JavaScript

  25. ࣮ફྫ1 Array [1,2,3,4,5]ͷ֤ཁૉΛ10ഒͯ͠ग़ྗ

  26. Bad. i͕for blockͷ֎ʹ΋ӨڹΛٴ΅͢

  27. iͷείʔϓ͕for block಺ʹͳͬͨɻ
 Ͱ΋΋͏ͪΐͬͱ؆ܿʹॻ͖͍ͨɻ
 arrͷཁૉΛॻ͖׵͑ͯΔͷ΋ා͍ɻ

  28. ࣮૷͸1ߦ
 arrΛมߋ͠ͳ͍ɻGood

  29. ࣮ફྫ2 Array [1,2,3,4,5]ͷ֤ཁૉͷ߹ܭ஋Λग़ྗ

  30. letͱfor loop

  31. for-ofΛ࢖͏

  32. Array.prototype.reduceΛ࢖͏ɻ
 sumΛ࠶୅ೖෆՄʹͰ͖ͯ҆શɻ

  33. ݱ୅෩JS ม਺είʔϓ͸Ͱ͖Δ͚ͩখ͘͞ɺͰ͖Δ͚ͩ࠶୅ೖෆՄʹ͢Δ Ұ౓࡞ͬͨobject͸มԽͤ͞ͳ͍ͷ͕ਖ਼ٛ ෭࡞༻ͷൃੜΛආ͚Δ Immutable.jsΛ࢖ͬͯcollection͸͢΂ͯimmutableͰ͋Δ͜ͱΛલఏʹ͢Δ ྲྀ೿ ArrayͳͲʹศརͳmethod΋࢓༷Ͱ௥Ճ͞Ε͍ͯΔ(https://github.com/tc39/ proposals)

  34. ࣮ફྫ3
 ඇಉظ+varͷා͞Λମݧ(ϥΠϒίʔσΟϯά)

  35. Array΋Object΋immutableʹ͍ͨ͠ਓ΁

  36. Object.freeze()ͰखܰʹObject΍ArrayΛimmutableʹ

  37. Immutable.jsͷclassΛ࢖͏

  38. Immutable.jsͬͯʁ https://facebook.github.io/immutable-js/ WebϑϩϯτΤϯυͰ͸͓ೃછΈͷFacebook੡ JavaScriptͰimmutableͳܕΛѻ͑ΔΑ͏ʹ͢ΔͨΊͷϥΠϒϥϦ Object΍ArrayͳͲɺJavaScriptͷbuilt-inͳσʔλܕΛimmutableʹ ͢ΔΞϓϩʔνͰ͸ͳ͘ɺؔ਺ܕݴޠ͔Β༌ೖͨ͠ಠࣗͷσʔλܕ Λѻ͏ List, Stack, Map,

    OrderedMap, Set, OrderedSet,
  39. ·ͱΊ var͸΋͏͍Βͳ͍ ·ͣconstͰॻ͍ͯɺͲ͏ͯ͠΋ඞཁͳΒletΛ࢖͏ ෭࡞༻Λආ͚Δ͜ͱ͕ਖ਼ٛͩͱ͍͏࣌୅ ؔ਺ܕݴޠͷύϥμΠϜ͕JSͷੈքʹ༌ೖ͞ΕͯΔ TypeScript + Rx.js + Immutable.jsͱ͔΍Γ͸͡ΊΔͱ׬શʹผݴޠ