grayshine
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # <font class="h2">var、let、const 的差異</font> ###### tags: `javascript` <style> .h2 { background: linear-gradient(135deg,#fff,#537479) ; color: #537479; display:block; padding: 6px 5px; border-radius: 4px; } .h3 { background: linear-gradient(180deg,#fff 50%,#c9d5d4) ; color: #537479; display:block; padding: 6px 5px; border-bottom: 3px solid #537479; } .h4 { color: #537479; font-weight:bold; font-size:1.1em; } </style> :::info ES6 採用 (區塊)Block Level Function Declarations 界定 Function 範圍,由於 IE8~IE10 不支援 ES6,仍然採用 hoisting 界定 function 範圍。 ::: | | 重複賦予值 reassigned |拉升<br>hoisting | 作用域 Sope |window | 重複宣告<br>redeclared | | ----- | ---------------------- | -------------------------------- | -------------------------- | --- | -------- | | var | 可以 | 可以先取值後宣告(undefined) | 全域/函式作用域 (Globally Sope/Function Scope) | 可存在 | 可以 | | let | 可以 | 須先宣告才能取值(否則會出錯) | 區塊作用域(Block Scope) |不可存在| 不可以 | | const | 宣告為常數,不能再做修改 | 須先宣告才能取值(否則會會出錯) | 區塊作用域(Block Scope) |不可存在 | 不可以 | <br> ### <font class="h4">var</font> - var宣告的變數,變數的作用域(Scope)以==函式區塊==分界 - 變數中的資料可以變動 <br> ### <font class="h4">let</font> - let宣告的變數,變數的作用域(Scope)以==程式區塊(大括號)==分界 - 宣告變數,可以暫時不給資料 - 變數中的資料可以變動 <br> ### <font class="h4">const</font> - `const <常數名稱>=常數資料` - const宣告一定要指定資料 - 常數資料不能變動(==唯獨屬性==) - ==const可以指定物件,並修改物件裡面的值,但不能再賦予新的值到此物件裡== <br> ### <font class="h3">重複賦予值 reassigned</font> <br> :::info - var的作用域以函式區塊區分 **var、let可以重複賦予值** ```javascript function fn(){ var a = 1; var a = 0; } ``` ::: :::info const無法重新賦予值,如果不想值被更動可以使用const ```javascript const b = 0; b = 1; console.log(b); // 會報錯Assignment to constant variable ``` ::: :::info **let與const的差異** - 當是「值」時,值會變的使用let,值不會變的使用const - 是「物件」的話,指向會變的用let,指向不會變的使用const **物件傳參考特性(by reference)** ```javascript const a = { name: '卡斯伯'} //宣告一個物件 a.name = 'Ray' //改變物件的值 ``` 這要寫是正確的 `{}`為「物件」,當宣告一個物件時,因為物件有傳參考特性,所以建議使用const,而不用let <br> <br> **修改整個「物件」的話 不可以用 const 宣告** ```javascript const a ={name:'卡斯柏'} a = {name:'Ray'} ``` 這樣寫會出錯,因為物件傳參考 `{}`為物件,產生一個新的物件,就會有一個新的參考位置(記憶體空間),:bulb:cont不勻許「物件指向」被改變,「物件指向」會被改變使用let ![](https://i.imgur.com/SzZxxjL.jpg =350x) :BULB:結論:可以用 const 就用 const 不要都用 let 宣告 ::: <br><br><br><br> ### <font class="h3">範例:</font> ```javascript if (true) { function foo() { return "a"; } } else { function foo() { return "b"; } } console.log(foo()); ``` <br><br><br><br> ### <font class="h3">作用域/範疇 scope</font> ![](https://i.imgur.com/uIKNuTX.png)([圖片來源)](https://codeburst.io/declaring-variables-in-es6-javascript-60ea37e38765) ![](https://i.imgur.com/HYW6JWy.png =500x )([圖片來源)](https://codeburst.io/declaring-variables-in-es6-javascript-60ea37e38765) :::info :bulb:未宣告為一個**全域「屬性」** (:bulb:屬性與變數不同) ```javascript function fn() { a = 0; } fn(); // 可以取到 a 的值為0 ``` 沒有宣告的話,會造成全域汙染,變得髒。要盡可能去宣告變數 ::: 區域變數有分函式作用域(Function Scope)、區塊作用域(Block Scope) :::info - var在函數內宣告時作用域是函式作用域,這意味著它們僅在創建它們的函數內可用 - var在函數外宣告時,作用域是全局的 ```javascript function fnB() { var a = 1; } fnB(); console.log(a); // 上方結果會是 a is not defined(報錯),因為function內容跑完後裡面的內容記憶體空間會被清除 ``` ```javascript function fnB(){ var a = 1; console.log(a); } fnB()//可以取到1 ``` 因為每個函式都有自己的作用域 所以兩個函式的 a 都只在自己的作用域中 不會互相衝突 這也是我們要宣告變數的原因 當我們沒有宣告變數的時候就可能造成全域的污染 ::: :::info 使用 var 時,若在「區塊作用域block`{}`」宣告,仍然可以在區塊作用域之外拿取。如下: ```javascript { var v1 = "hello"; } console.log(v1); //hello ``` 如果是使用 let 或 const,則受區塊作用域限制,無法於區塊之外拿取,會報錯。 ```javascript function fn(){ let a = 1; } console.log(a); //會取不到值(not defined)報錯 ``` ```javascript for (let i =0; i <10; i++){ } console.log(i); //會取不到值(not defined)報錯 ``` :bulb:相較var,let的作用域較穩定,不容易出錯 ::: <br> ### <font class="h3">拉升 hoisting</font> :arrow_right:[拉升](https://hackmd.io/@grayshine/rk9hv-TBt) <br> :::info 我們在初始化的過程中嘗試去取值,會取得 `undefined`,這就是 hoisting ```javascript console.log(a); // 輸出 undefined var a = 1; console.log(a); // 輸出 1 ``` ::: :::info **let、const須先宣告才能取值** ```javascript function fn(a){ console.log(a); //此段為暫時性死區TDZ let a = 2 ; console.log(a); } fn(1) //這段使用let會出錯,因為let須先宣告才能取值 ``` :bulb:暫時性死區TDZ(temporal dead zone) 結果會報錯,不勻許在宣告值之前去取得這個值 ::: <br> <br> ### <font class="h3">window(全域物件)</font> <br> :::info **var可以存在window上面,let不可以** ```javascript var a =0; let b =1; console.log(window); //會發現window點開a=o,找不到b ``` ::: ### <font class="h3">重複宣告redeclared</font> :::info - var 重複宣告也不會報錯 ```javascript function fn() { var a = 1; var a = 0; } fn(); // var 重複宣告也不會報錯 ``` <br> ```javascript let a = 0; let a = 1; //會出錯(has a ready been declared) ``` ::: --- 參考文章 https://www.youtube.com/watch?v=FGdKdn_CnWo&ab_channel=%E5%85%AD%E8%A7%92%E5%AD%B8%E9%99%A2 https://codeburst.io/declaring-variables-in-es6-javascript-60ea37e38765

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully