expression VS statement

題外話

Syntax (語法 / 文法)

she cooks an egg.
she is a cook.
* syntax
  * statements
    * expression statements
  * expressions

expression (表達式)

會產生一個值(會回傳一個值)

  • 物件實字 (object literals)
{ key1: 'value1', key2: 'value2'}
  • function expression
var add = function(x, y) {
  return x + y;
}
add(1, 2);
  • invoking function expression (立即呼叫函式)
(function sayHello() {
    alert("hello!");
})();

statement (陳述式)

  • 完成某項任務的操作
  • 會產生附影響 (side effect)

例如:

var x // 宣告
x = 1; // 賦予值

// 條件判斷
if(x > 0){
  console.log('hi hi');
}

statement block

static void main(){
  var counter;
  counter = 1;
  // do something...
  // do something...
  // do something...
  // do something...
}

function declaration / function statement

function add(a,b) {return a + b};

function hi(name) {
  console.log('hi ' + name);
}
hi('alincode');

declaration statement

var message;

expression statement

  • expression statements 屬於一種特殊的 statements,會產生一個值,並完成某項任務。
x += 1;

counter++;

如果在始於 statement 位置的地方放入 expressions,就叫做 expression statement。

expression 與 statement 之間明顯的差異

  • statement 位置,一定可以放 expression,但 expression 位置,大多數情況都不能放 statement。
var x = 1;
var y = 2;

if(x >= 0){
  x = y;
} else {
  x = -y;
}
  • expression:一定有回傳值
var x = 1;
var y = 2;

var x = (y >= 0 ? y: -y);

function expression VS function statement

function expression

var addFunc = function(x, y) {
  return x + y;
}

function declaration / function statement

function hi(name) {
  console.log('hi ' + name);
}
hi('alincode');

延伸閱讀

results matching ""

    No results matching ""