JavaScript specials

Code structure

alert('Hello'); alert('World');

alert('Hello')
alert('World')

alert("There will be an error after this message")
[1, 2].forEach(alert)

function f() {
  // no semicolon needed after function declaration
}

for(;;) {
  // no semicolon needed after the loop
}

Strict mode

'use strict';

...

Variables

  • let

  • const primitive 值不會被改變。

  • var 老式寫法

變數命名

  • 變數名稱只能用字母、數字、$、_

  • 有多個單字通常使用 camelCase 命名

  • 第一個字不能是數字

  • 有分大小寫

  • 可以用其他語言,但不推薦,因為可能有其他國家的人要閱讀。

  • 有幾個名稱 list of reserved words 已經被使用,無法作為變數。

7 種資料類型

  • number 整數或有小數點的數字。

  • string 字串。

  • boolean true / false

  • nullnull 空的或不存在。

  • undefinedundefined 值沒有被指定。

  • object 複雜的資料結構。

  • symbol 特殊標籤的資料類型。

typeof 顯示資料類型,有以下 2 種例外。

Interaction

  • prompt(question, [default]) 問問題返回使用者的答案,選擇 ok 或 cancel。

  • confirm(question) 問問題返回布林值,選擇 ok 或 cancel。

  • alert(message) 顯示訊息。

Operators

  • Arithmetical + - * / % **

  • Assignments a = 2 a += 2

  • Bitwise

  • Ternary cond ? resultA : resultB

  • Logical operators && || !

  • Comparisons > < == != ===

  • Other operators ,

Loops

The “switch” construct

Functions

Last updated

Was this helpful?