# 何謂表達式(Expression)與陳述式(Statement)? ###### tags: `JavaScript` `JS 直播班 - 2021 秋季班` ## 陳述式(statement) 一定會做事,但<font color="red">**不會產生數值**</font> 不能放在JS會產生出數值的地方 EX: 函數的return或是parameter的地方 ### 以下為常見的陳述式 #### 流程控制 * block * break * continue * if...else * switch * try...catch * throw #### 宣告 **宣告會讓整個函式內容在語法解析階段都會保留進記憶體空間,所以屬於函式的陳述式, JS會幫你保留記憶體空間** * let * const * var ## 表達式(運算式) <font color="red">**任何一段可以取得一個值的程式碼**</font> 表達式的<font color="red">**執行結果會回傳一個值**</font>,而該值不一定要賦予給任一變數。譬如運算、賦值、呼叫函式等 概念上,有兩種不同型態的運算式: 1. 將一個值指定給一個變數 ```=Javascript let x; //這是陳述式 x=7; //這是表達式,賦予7給x ``` 2. 只為了取得值而解析的運算式。 ```=javascript 3+4 //這個運算式利用+把3跟4加起來 ``` ## 函式陳述式 & 函式表達式 ### 函式陳述式 Function statement 藉由直接給定名字來直接宣告一個函式,JS幫你保留記憶體空間 <font color='red'> **整個函式內容在語法解析階段都會保留進記憶體空間** **函式宣告在全域環境具有 提升 (Hoisting) 的效果,能在宣告之前呼叫函式。** </font> ```=javascript gogo(); function gogo(){ //do something } ``` ### 函式表達式 Function expression 把一個匿名函式指派給一個變數 這種宣告方式的函式內容不會在一開始就被提升 (Hoisting),會被提升的只有該變數而已。 <font color='red'> **執行階段,才會把函式內容指派給變數** </font> ```=javascript var functionExpression = function(){ //doSomeThing } ``` ### 什麼是提升 Hoisting? 簡單來說,提升是JS裡面獨特的行為,<font color='red'>**宣告一個變數或是函式之前,就先使用它,而且不會出錯**</font> ```=JavaScript catName("danny123"); function catName(name) { console.log("My cat's name is " + name); } /* 上面程式的結果是: "My cat's name is danny123" */ ``` 詳細內容傳送門1: [JS 原力覺醒 Day06 - 提升 Hoisting](https://ithelp.ithome.com.tw/articles/10218457) 詳細內容傳送門2: [提升(Hoisting)](https://developer.mozilla.org/zh-TW/docs/Glossary/Hoisting) ## 參考資料 [Weird-JavaScript 20:函式陳述式與函式表達式](https://luffy.website/2019/08/15/weird-JavaScript-20/) [陳述式與宣告](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Statements) [JS 原力覺醒 Day07 - 陳述式 表達式](https://ithelp.ithome.com.tw/articles/10218937) [運算式與運算子](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Guide/Expressions_and_Operators#%E9%81%8B%E7%AE%97%E5%BC%8F) [提升(Hoisting)](https://developer.mozilla.org/zh-TW/docs/Glossary/Hoisting) [JS 原力覺醒 Day06 - 提升 Hoisting](https://ithelp.ithome.com.tw/articles/10218457)
×
Sign in
Email
Password
Forgot password
or
Sign in via Google
Sign in via Facebook
Sign in via X(Twitter)
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
Continue with a different method
New to HackMD?
Sign up
By signing in, you agree to our
terms of service
.