---
# System prepended metadata

title: Learning JS from zero

---

# Learning JS from zero


I've been struggling with my work in school writing websites recently since I've never really learned javascript seriously

Now I've done my CS master entrance exams ,I am going to work my way up to a master of Javascript

Let's start with the simple tutorial from codecademy

## Basics

* **console**: it's a keyword in js, refers to an object
    ```javascript=
    console.log(5)
    ```
    the above code will print 5 on the console



### Data Types

There're 7 fundamental data types in JS

1. Number: any number no matter it's integer or floating point
2. String
3. Boolean
4. Null: represents the intentional absence of a value
5. Undefined: also represents the absence of a value. it means that a given value doesn't exist
6. Symbol
7. Object: Collections of related data


### String Concatenation
```javascript=
console.log('Hello'+' World')//prints out Hello World
```

### Properties

When you introduce a new data into a JS program, **the browser saves it as an instance of the data type**


### Variables

* **var**: JS keyword that declares a new variable

* variable names can't start with numbers

```javascript=
var a = 10;
let b = 'Hello';
```

* **let** : signals that the variable can be reassigned a different value

* we can declare a variable without assigning the variable a value, **it'll be automatically initialized with a value of undefined**

```javascript=
const CantChange = true;
```

* like a normal variable, but it can't be reassigned with other value;

* **const variable must be assigned a value when declared**. If you try to declare a const variable without a value, you'll get a SyntaxError

:::info
**Javascript ES6**
the version of JS is following the specifications in the 6th edition of ECMAScript
:::

### Array

* using let or const to declare an array has small difference
```javascript=
let a=['hi','yo'];
const b = ['yes','no'];
```

* you can change the element of array b, but you can't assign a new array or value to b;

### Callback function

* functions that are passed as parameters into some higher-order function





## Objects

### Object literals

```javascript=
let obj = {
    color : 'blue',
    'space bar' : 'yes'
    fun: function(){
        console.log('hi')
    }
};
```


### Getter and setter

* https://www.scaler.com/topics/javascript/getter-and-setter-in-javascript/


### Factory functions

* 可以產生數個object的function

## Async 非同步

https://www.codecademy.com/article/wix-why-learn-asynchronous-javascript

* https://www.codecademy.com/learn/velo-by-wix-using-async-actions-for-the-backend


* Asynchronous operation is one that allows computer to move on to other tasks while waiting for the asynchronous operation to complete


### Promise Object

* Promise object represent the eventual outcome of an async operation

* Promise 有三種state
    1. Pending: the initial state, the operation hasn't completed yet
    2. Fulfilled: the operation has completed successfully and promise now has a resolved value
    3. Rejected: the operation has failed and has a reason for the failure

* 創建promise object

```javascript=
const executorFunction = (resolve, reject) => { };
const myFirstPromise = new Promise(executorFunction);
```

* 上述程式碼當中，Promise constructor會接收一個function來作為它的參數，此function又稱為executor，當constructor被呼叫的時候，executor會自動開始非同步地執行

* executor會有兩個參數，resolved()跟reject()

* resolve()有一個參數，會把promise的status從pending改成fulfilled
    reject()有一個參數，會把error當成參數，把status改成reject

更實際的例子如下
```javascript=
const executorFunction = (resolve, reject) => {
  if (someCondition) {
      resolve('I resolved!');
  } else {
      reject('I rejected!'); 
  }
}
const myFirstPromise = new Promise(executorFunction);
```

* 若someCondition被滿足，通常是async operation的執行結果，則執行不同的function來改變state


* 還有setTimeout()這個API，若將delay設為兩秒，則實際的delay不一定是兩秒
    原因如下
    Async Javascript使用event-loop
    兩秒鐘後，該function會被加到正要被執行的code當中，在他執行之前，所有其他synchronize的code都會被執行，然後所有在他之前的code也都會被執行，所以可能超過兩秒鐘

```javascript=
console.log('1');
setTimeout(()=>{console.log('2');}, 0);
console.log('3');
//Expected output: 1 3 2
```

* 為何delay設成0，結果還是1 3 2
* https://pjchender.dev/javascript/js-event-loop-stack-queue/?fbclid=IwAR0dZqTQFpeSzZq3Pa192f20Rg49uh7n9P_pvX7_n4iqKeHsoU8HKev2HBo

* 當promise settle之後，要做甚麼事可以使用.then()

* .then()是一個higher order function，接收兩個callback function，稱為handlers
    第一個handler稱為onFulfilled，是一個success handler，會包含promise被resolve之後要做的事
    第二個稱為onRejected，是一個failure handler


* .then() always return a promise

檢查以下例子
```javascript=
const prom = new Promise((resolve, reject) => {
  resolve('Yay!');
});
 
const handleSuccess = (resolvedValue) => {
  console.log(resolvedValue);
};
 
prom.then(handleSuccess); // Prints: 'Yay!'
```

* 以上程式碼可以做這樣的解讀
    handleSucess只是一個普通的function，prom則是一個async function，prom.then()接收handleSucess作為參數，此時若promise被resolve，則會將resolve的參數作為參數送入handleSucess當中

* 通常我們不會知道Promise會resolve還是reject，所以兩種case都要寫好

```javascript=
let prom = new Promise((resolve, reject) => {
  let num = Math.random();
  if (num < .5 ){
    resolve('Yay!');
  } else {
    reject('Ohhh noooo!');
  }
});
 
const handleSuccess = (resolvedValue) => {
  console.log(resolvedValue);
};
 
const handleFailure = (rejectionReason) => {
  console.log(rejectionReason);
};
 
prom.then(handleSuccess, handleFailure);
```

* https://eyesofkids.gitbooks.io/javascript-start-es6-promise/content/contents/ch2_before_start.html

* promise 結構是一種異步執行的控制流程架構


* **chaining promises**

* https://ithelp.ithome.com.tw/articles/10231597

* promise.all() 使用concurrency的概念，也是非同步，但不在乎執行順序，只要全部做完就好，盡量最大化efficiency

### async and await

* async function使得原本ES6版本使用callback或promises處理非同步的code更為簡潔易讀，不然原本一堆nested跟chaining看了眼睛快脫窗

* async有三種可能的return value
    1. if there's nothing return from the function, it'll return a promise with a resolved value *undefined*
    2. if there's a non-promise value return from the function, it'll return a promise resolved to that value
    3. if a promise returned from the function, it'll simply return that promise

```javascript=
async function fivePromise() { 
  return 5;
}
 
fivePromise()
.then(resolvedValue => {
    console.log(resolvedValue);
  })  // Prints 5
```

* 上述程式碼看起來fivePromise()是return 一個5，但實際上他是return 一個promise with resolved value 5

* await operator can only be used inside an async function
    it returns a resolved value of a promise
    await halts the execution of the async function until a given promise is resolved

```javascript=


let myPromise = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('Yay, I resolved!')
    }, 1000);
  });
}


async function noAwait() {
 let value = myPromise();
 console.log(value);
}
 
async function yesAwait() {
 let value = await myPromise();
 console.log(value);
}
 
noAwait(); // Prints: Promise { <pending> }
yesAwait(); // Prints: Yay, I resolved!
```

* 上述程式碼當中，myPromise是一個Promise物件，因此他是非同步地執行
    當noAwait() function第一次呼叫它時，它不會等待myPromise被resolve，而是繼續往下執行
    因此需要加上await，才能停在那邊等到myPromise得到結果
    
    甚至兩個function當中的value得到的return type也是不同的，noAwait的value得到的是一個Promise object，而yesAwait()得到的則是resolved value of a promise

* async await最重要的應用之一，在於我們有很多互相依賴的promises，例如做一系列的web request包含query databases，等等。
    此時若用之前的promise.then()等方式會造成chaining，難以閱讀(當然比nested challback好)

* 若再async function存在數個獨立的function，我們希望他們同時執行，若加上await則會導致一次只能做一件事

```javascript=
async function waiting() {
 const firstValue = await firstAsyncThing();
 const secondValue = await secondAsyncThing();
 console.log(firstValue, secondValue);
}
 
async function concurrent() {
 const firstPromise = firstAsyncThing();
 const secondPromise = secondAsyncThing();
console.log(await firstPromise, await secondPromise);
}
```

* 將waiting改成concurrent就能解決這問題


* **failing fast** : 當任一個action失敗的時候，剩下還沒做完的不會繼續，會直接回傳錯誤












