> For the complete documentation index, see [llms.txt](https://mistborn.gitbook.io/til-coding/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://mistborn.gitbook.io/til-coding/javascript/javascript-specials.md).

# JavaScript specials

## Code structure

```javascript
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

```javascript
'use strict';

...
```

## Variables

* let&#x20;
* const primitive 值不會被改變。
* var 老式寫法

變數命名

* 變數名稱只能用字母、數字、$、\_
* 有多個單字通常使用 [camelCase](https://en.wikipedia.org/wiki/CamelCase) 命名
* 第一個字不能是數字
* 有分大小寫
* 可以用其他語言，但不推薦，因為可能有其他國家的人要閱讀。
* 有幾個名稱 [list of reserved words](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords) 已經被使用，無法作為變數。

7 種資料類型

* `number` 整數或有小數點的數字。
* `string` 字串。
* `boolean` `true` / `false` 。
* `null` – `null` 空的或不存在。
* `undefined` –  `undefined` 值沒有被指定。
* `object` 複雜的資料結構。
* `symbol` 特殊標籤的資料類型。

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

```javascript
typeof null == "object" // error in the language
typeof function(){} == "function" // functions are treated specially
```

## Interaction

* &#x20;prompt(question, \[default]) 問問題返回使用者的答案，選擇 ok 或 cancel。
* &#x20;confirm(question) 問問題返回布林值，選擇 ok 或 cancel。
* &#x20;alert(message) 顯示訊息。

## Operators

* Arithmetical `+ - * / % **`&#x20;
* Assignments `a = 2` `a += 2`&#x20;
* Bitwise&#x20;
* Ternary `cond ? resultA : resultB`
* Logical operators `&& || !`
* Comparisons `> < == != ===`&#x20;
* Other operators `,`

## Loops

```javascript
// 1
while (condition) {
  ...
}

// 2
do {
  ...
} while (condition);

// 3
for(let i = 0; i < 10; i++) {
  ...
}
```

## The “switch” construct

```javascript
let age = prompt('Your age?', 18);
// use ===
switch (age) {
  case 18:
    alert("Won't work"); // the result of prompt is a string, not a number

  case "18":
    alert("This works!");
    break;

  default:
    alert("Any value not equal to one above");
}
```

## Functions

```javascript
// Function Declaration
function sum(a, b) {
  let result = a + b;

  return result;
}

// Function Expression
let sum = function(a, b) {
  let result = a + b;

  return result;
}

// Arrow functions
// expression at the right side
let sum = (a, b) => a + b;

// or multi-line syntax with { ... }, need return here:
let sum = (a, b) => {
  // ...
  return a + b;
}

// without arguments
let sayHi = () => alert("Hello");

// with a single argument
let double = n => n * 2;
```
