# 網頁前端面試準備
###### tags: `前端`
## 面試題目
1. npm 是什麼?為什麼需要用到它?可以不用它嗎?
>**NPM(Node Package Manager)**,是一個**線上套件庫**,**專門下載各式各樣的javascript套件來使用**,可以快速地下載想要的套件來使用。可以不用npm,但是就會減少便利性。
2. npm 和 直接從網路上載下來 library 檔案再用 script 引入,這兩個差別是什麼。
>利用npm來管理套件**更為方便**,且相較於直接引入script,npm載入的套件**有經過打包,所以檔案體積較小,縮短加載的時間。**
3. package.json 和 package-lock.json 的差異。當協作的時候,package-lock.json 需不需要傳上 GitHub 。
> - **package.json**: 記錄你專案中所需要的**所有模組**,**但這些模組所依賴的子模組的資訊並不會被記錄。**
> - **package-lock.json**: 是在 `npm install`時候生成的一份文件,用以**記錄當前狀態下實際安裝的各個npm package的具體來源和版本號,包括主模組和所有依賴子模組。**
>所以,總結來說,**為了系統的穩定性考慮,每次執行完npm install之後會建立或者更新package-lock檔案。** 該檔案記錄了上一次安裝的具體的版本號,相當於是提供了一個參考,**在出現版本相容性問題的時候,就可以參考這個檔案來修改版本號即可。**
>
>**package-lock.json 需要上傳到git**,以保證其他人npm install時安裝的依賴能夠保持一致
4. 物件導向的基本概念。
5. 說說為何需要使用 React,和原生 JS 的差別是什麼。
6. React 的 component,為何要 extends Component,為何要用 constructor,super 的功用又是什麼。
>super 方法可以呼叫繼承父類別的建構子
http://cheng.logdown.com/posts/2016/03/26/683329
7. Two-way binding 是什麼?React 如何實作?
>Two-way binding(雙向的資料繫結),由於很多時候 DOM 上顯示的值必須和某個 state 中的值一致,所以**所謂的 Two-way binding 即程式在背後自動幫您同步這兩個值。改變 form 時 model 會修正,更新 model 後 form 的 UI 也會跟著更新。**
>
>React 提供了 **ReactLink**: 這個語法糖衣讓您可以輕鬆完成這樣的功能,或者我們可以說 ReactLink 就是幫您連結資料來源到 React 的 state。
8. gulp 和 webpack 的差異?
> - **gulp** 是 **task runner**
> - **Webpack** 是 **module bundler**
>**webpack**: 是一個**模組打包工具**。幫我們**編譯Preprocess成瀏覽器看得懂的內容然後打包成一包的完成檔案然後拿去server 上傳上去。**
9. JavaScript 的 == 和 ===的差異?
>`==`會對**被判別的變數做轉換型別的動作**(coercion又稱為implicit type conversion),轉換型別後值一樣就可以。`===`則是**要求型別也要一樣**
10. JavaScript 的 undefined 和 null 的差異?
>undefined 代表的是未定義,比如**變數無賦予值的話該變數預設就會是 undefined**。null 的意義是**空值,是讓開發者用來宣告變數沒有值。**
11. Arrow function 和一般的 function 寫法的差異?
```
(參數1, 參數2, …, 參數N) => { 陳述式; }
(參數1, 參數2, …, 參數N) => 表示式;
// 等相同(參數1, 參數2, …, 參數N) => { return 表示式; }
// 只有一個參數時,括號才能不加:
(單一參數) => { 陳述式; }
單一參數 => { 陳述式; }
//若無參數,就一定要加括號:
() => { statements }
```
>The biggest difference between the traditional function expression and the arrow function, is **the handling of the `this` keyword.**
>By general definition, the `this` keyword always **refers to the object that is calling the function.**
>**Arrow Functions 會自動綁定 (bind) `this` 到 `宣告(定義)` Arrow Functions 當時的環境 (context)。**
>
>也就是說,**箭頭函數當中的 this 是`定義`時的對象,而不是使用時的對象。**
>**In the arrow functions, there is no binding of the `this` keyword.**
>The `this` keyword inside an arrow function, does not refer to the object calling it. It rather inherits its value from the parent scope which is the `window` object in this case.
```
var demo = {name: 'Eric',
getName: ()=>{return this.name},
getName2: function(){return this.name}};
console.log(demo.getName()); //"CodePen",因為定義的時候是global(window)
console.log(demo.getName2()); //"Eric"
```
```
function Person(){
this.age=25;
this.getAge = function(){return this.age};
this.getAge2 = ()=>{return this.age};
}
var p1 = new Person();
console.log(p1.getAge()); //25
console.log(p1.getAge2()); //25,因為箭頭函式定義的時候在Person裏頭,所以this會找到
```
12. JavaScript 的 ES5 和 ES6 語法有哪些差別?
> - ES5: `var`,ES6: `let`、`const`
> - ES6多了`symbol`,用來表示獨一無二 (unique) 的值。
> - ES6多了 `arrow function`
>
>
>
>https://www.geeksforgeeks.org/difference-between-es5-and-es6/
13. git 的 rebase 和 merge 的差異?
>**Merge 和 rebase 都是合併歷史記錄**
- **Merge**: 修改內容的**歷史記錄會維持原狀**,但是**合併後的歷史紀錄會變得更複雜。**

- **Rebase**: 修改內容的**歷史記錄會接在要合併的分支後面,合併後的歷史記錄會比較清楚簡單,但是,會比使用 merge 更容易發生衝突。**

14. setTimeout() 第二個參數如果是 1000 是什麼意思?實際上真的是 1000 過後就執行了嗎?為什麼?
>1000是1000ms(1秒)的意思。
>
>ex: `window.setTimeout(console.log("Hello!"), 1000);`
>
>**`setTimeout()` 會先判斷第一個參數是否為 「function」,如果不是,則會嘗試將它當作字串處理。**
>
>換句話說,會將 `console.log("Hello!") `執行後的回傳值轉為字串,......欸,沒有回傳值,那就是 undefined, 於是`window.setTimeout(console.log("Hello!"), 1000);`實際上是`window.setTimeout("undefined", 1000);`於是 1000ms 到了就什麼事都沒發生。而 "Hello" 則是在呼叫 console.log() 的當下就會被印出。
15. 今天我要串一個 API,我要怎麼在傳回來的資料中,篩選我想要的欄位資料,並且去為這些欄位的值開頭新增 $ 字號?
```
arr = [1,2,3,'abc'];
farr = arr.filter((ele,i)=>{
return ele>0;
}).map((ele)=>{
return '$'+ele
})
console.log(farr) // ["$1", "$2", "$3"]
```
16. Redux 在幹嘛的?它的整個概念與架構是?
17. 說明 MVVM 是什麼?
>**MVVM (Model-View-ViewModel)**
> - **Model**: 管理資料來源(ex:API、資料庫...)
> - **View**: 顯示UI、接收使用者行為
> - **ViewModel**: 從Model取得View所需要的資料
18. class 裡面,要使用繼承時,constructor 裡面為什麼要放 super(),它的功用是什麼?
19. JavaScript 要怎麼在 class 裡設定 `private` function?
>1. 用底線開頭命名
>2. 使用closure
>3. 使用WeakMap
>4. 使用Symbol
>5. 使用Math.random
https://tw.twincl.com/javascript/*6937
20. React 中,既然 Parent Component 可以用 props 的機制傳遞東西給 Children Component ,那反過來說,Children Component 要怎麼傳東西給 Parent Component?
21. Promise 是什麼?它在做什麼的?
>所謂的 Promise,簡單來說它是一個**等待非同步操作完成的物件**,當事件完成時,Promise 根據操作結果是成功、或者失敗,做相對應的處理動作。
```
const myFirstPromise = new Promise((resolve, reject) => {
// 執行一些非同步作業,最終呼叫:
//
// resolve(someValue); // 實現
// 或
// reject("failure reason"); // 拒絕
});
```
Promise 物件生成後,可以用 then() 方法來綁定當 fulfilled 或 rejected 狀態時,分別要執行的函數。
then() 方法接受兩個函數作為參數:
- 第一個函數是當 Promise 狀態變為成功時會被調用
- 第二個函數是當 Promise 狀態變為失敗時會被調用,這個參數是選擇性的不一定需要
```
promise.then(function(value) {
// 當狀態是 fulfilled (成功) 時,執行這個函數
// value 是透過 resolve() 傳進來的參數
}, function(error) {
// 當狀態是 rejected (失敗) 時,執行這個函數
// error 是透過 reject() 傳進來的參數
});
```
22. Promise 有哪些狀態?
>1. pending - 初始狀態 (進行中)
>2. fulfilled - 事件已完成
>3. rejected - 事件已失敗
23. 跨站請求你知道嗎?因這個緣故那要設定什麼才可以串接 API?
>**CSRF(Cross Site Request Forgery): 跨站請求攻擊。** 攻擊者通過後台某介面的請求網址,讓使用者點擊而連結或腳本的方式,使請求位址加載。
>
>攻擊方法: 使用者登錄 A 網站,瀏覽器會記錄 Cookies,如果使用者未登出或 Cookies 並未過期 (使用者關閉瀏覽器不代表網站已登出或 Cookies 會立即過期)。在這期間,如果使用者造訪 B 網站,點擊攻擊者的連結,便會向 A 網站發出某個請求,**A 網站的伺服器接收後會誤會以為是使用者的合法操作。**
>https://blog.techbridge.cc/2017/02/25/csrf-introduction/
24. (承上題)那為什麼你說的 JSONP 那幾個東西可以直接拿取資料?
>**JSONP (JSON with Padding)**: JSONP 是 JSON 的一種使用模式,可以讓一個網頁從其他的網域 (cross-domain) 請求資料,繞過 AJAX 因為有瀏覽器安全性限制無法跨網域使用的問題 (same-origin policy)。
>
>**利用 `<script>` 標籤可以跨網域請求的特性。**
>
>https://www.fooish.com/json/jsonp.html
>
25. RESTful API 是什麼?
>是一種網頁API的**設計風格(非標準)**。
>- 用一個**唯一的 URL 定位資源**,將動作藏在 HTTP 的 method 裡面,**統一API的接口**。
>- **無狀態(stateless):** 無狀態的意思,**即 Client 端自行保存狀態,在請求 Server 的時候,一併附上給 Server 端,Server 端無保存 Client 端的狀態資訊。**
HTTP 動詞(Verb):
- GET 讀取資源
- PUT 替換資源
- PATCH 更換資源部分內容
- DELETE 刪除資源
- OPTIONS 回傳該資源所支援的所有 HTTP 請求方法
- CONNECT 將連線請求轉換至 TCP/IP 隧道
- POST 新增資源
26. 可以說說今天使用者進入到一個網頁時,後台的處理發生什麼事嗎?
>Step 1:TCP 三向交握
- 瀏覽器: 嘿 伺服器你在嗎?
- 伺服器: 在唷!
- 瀏覽器: 好的收到,那我要開始傳資料囉~
>Step 2:瀏覽器請求、資料傳輸、渲染畫面
- 瀏覽器,送出第一次請求(Resquest)
- 伺服器,透過封包傳輸資料,每個封包上限約 1506 bytes。因此,一個請求可能會拆分成好幾個封包來回傳資源(Response)
** 封包就類似購物袋的角色,它會負責把資料拆分成好幾個封包來回傳資源(Response) **
- 瀏覽器,第一次渲染
>Step 3:TCP 四次揮手,結束連線
- 瀏覽器:好囉,資料都收到囉,可以關閉連線囉(申請關閉)。
- 伺服器:申請通過,那我也關囉。
- 伺服器:告知關閉,本身也開始關閉。
- 瀏覽器:收到關閉通知,回戳是否真正關閉,等候一段時間後,客戶端也關閉。
27. Cookie 和 Session 分別是什麼。
>**Cookie: 由Server端送給Client端的一小塊資料(文檔)。** **瀏覽器會儲存它並且在瀏覽器下一次發送要求的時候將它送回原本送來的伺服器,作為識別的用途。**
>
>**Session: 負責紀錄在 server端上的使用者訊息(敏感資訊),會在一個用戶完成身分認證後,存下所需的用戶資料,接著產生一組對應的 ID(Session ID),存入 cookie 後傳回用戶端。**
28. 你覺得使用者在一個網頁中輸入密碼之後,到傳送到後端這段期間,密碼有被加密嗎?是怎麼被加密的?
29. HTTP 與 HTTPS 有什麼差異呢?
>http是超文本傳輸協定,而https是經過加密的超文本傳輸協定,**S代表secure**。它們的區別也就在於一個**安全性**的問題。
> - HTTP 使用的是**80** Port 的協定(純文字模式)
> - HTTPS 走的是**443** Port 的協定(可通行二進制字元模式)
30. 可以說說 AJAX 是什麼嗎?
>**AJAX (Asynchronous JavaScript and XML): 非同步的javascript與XML技術**
>
> - **無須重新載入整個頁面**,便能對遠端伺服器發送請求 (請求會在瀏覽器背景執行)。
> - 讓你可以**只更新網頁中的一小部分內容**,也因為 server 返回的資料量更小,讓網頁反應速度更快。
> - 在跟 server 請求新內容同時,你可以**在頁面中繼續做其他操作,不用停住等待,**這種行為我們稱做**非同步 (asynchronous)**。
> - 未必要用XML,實務上反而更常用JSON
Example:
```
// 建立 XMLHttpRequest 物件
var httpRequest;
if (window.XMLHttpRequest) {
httpRequest = new XMLHttpRequest();
} else {
// 跨瀏覽器相容 IE6 以下
httpRequest = new ActiveXObject('Microsoft.XMLHTTP');
}
// AJAX callback
httpRequest.onreadystatechange = function() {
// 等狀態變成請求完成狀態
if (httpRequest.readyState === 4) {
// 只處理 server 返回正常的 HTTP 200 狀態
if (httpRequest.status == 200) {
// 解開 server 返回的 JSON 資料格式
var jsonResponse = JSON.parse(httpRequest.responseText);
// 更新頁面內容
document.getElementById('user').innerHTML = jsonResponse.userName;
}
else {
alert('ERROR - server status code: ' + httpRequest.status);
}
}
};
// 使用 HTTP GET 方法,從 URL /api/get_something 請求資料
httpRequest.open('GET', '/api/get_something');
// 送出 HTTP 請求
httpRequest.send(null);
```
jquery的ajax:
```
$.ajax({
url: "網址",
dataType: 'json',
success: function(data) {
console.log(data);
// 取得的遠端資料
}
});
```
31. 通常你都怎麼串接 API 的?使用什麼語法?(因為我回答 fetch/axios 所以接下題)
```
fetch('https://randomuser.me/api/')
.then(res=>{
console.log(res);
return res.json();
})
.then(res=>{
console.log(res);
})
.catch(err=>{
console.log(err);
})
```
32. (承上題)那這兩個語法實際上是怎麼運作的?
33. 你使用過 Async/Await 嗎?裡面的 try/catch 是怎麼運作的呢?
>The `async` keyword before a function has two effects:
>
>- Makes it **always return a promise**.
>- Allows `await` to be used in it.
>The `await` keyword before a promise makes JavaScript **wait until that promise settles**, and then:
>- If it’s an error, the exception is generated — **same as if `throw` error** were called at that very place.
>- Otherwise, it returns the result.
>**With `async/await` we rarely need to write `promise.then/catch`, but we still shouldn’t forget that they are based on promises, because sometimes (e.g. in the outermost scope) we have to use these methods.** Also Promise.all is nice when we are waiting for many tasks simultaneously.
>
```
async function f() {
try {
let response = await fetch('http://no-such-url');
} catch(err) {
alert(err); // TypeError: failed to fetch
}
}
f();
```
```
async function f() {
let response = await fetch('http://no-such-url');
}
// f() becomes a rejected promise
f().catch(alert); // TypeError: failed to fetch // (*)
```
https://javascript.info/async-await
34. JavaScript 的 ES6/ES7/ES8 等等這些分別代表什麼意思呢?
35. SSR 和 CSR 你知道嗎?他們分別在做什麼的呢?
> - **服務端渲染(SSR,Server-side Render)**: 瀏覽器傳送請求後,**server端把client端網頁和資料在後臺渲染解析,之後把渲染後的結果返回client端。**
>
> - **客戶端渲染(CSR,Client-side Render)**: 瀏覽器傳送頁面請求,**server端返回的是一個模板頁面,瀏覽器從上至下解析過程中需要傳送ajax請求獲取資料,最後再呼叫模板引擎(art-template等)渲染HTML結構,並把渲染後的結果新增到頁面指定容器中。**
36. (承上題)那 SSR 和 CSR 分別有什麼缺點呢?
>**SSR 有利於搜尋引擎優化(SEO)**,利於被網頁爬蟲抓取資料,多見於電商網站商品資訊獲取等。
>
>**CSR 不利於搜尋引擎優化(SEO)**,網頁資料非同步獲取,首頁載入時間長,使用者體驗相對較好,常用於不需要對SEO友好的地方。
* [補充-前後端分離與 SPA](https://blog.techbridge.cc/2017/09/16/frontend-backend-mvc/)
37. 你覺得為什麼需要使用 React?
38. 可以說說 React 的 state 和 props 的功能嗎?
>props(傳入後就不能修改)、state(隨著使用者互動而改變)
39. Redux 的 Middleware 可以解決 React 串接 API 非同步的問題,為什麼呢?
40. git 的 clone 和 pull 有什麼不同?
>都是把檔案從網路上下載到電腦,**差別是通常clone是第一次做,後續想更新線上版的資料,就會用pull就好。**
41. git 的 branch 要和 master 合併該怎麼做?
>使用`merge`or`rebase`兩種合併的方法,兩者差別詳第13題
42. React、Vue、Angular 有什麼差異和關係嗎?
43. 你在使用 React 的時候有感到什麼特別之處,可以舉例嗎?
44. 你用 React 在專案開發的時候都是怎麼做的呢?有用過 React 的快速搭建程式初始架構的相關指令或用法嗎?
* [2019 非本科、無經驗轉職網頁前端工程師的面試分享](https://medium.com/@eilin0603/2019-%E9%9D%9E%E6%9C%AC%E7%A7%91-%E7%84%A1%E7%B6%93%E9%A9%97%E4%B9%8B%E7%B6%B2%E9%A0%81%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%B8%AB%E7%9A%84%E9%9D%A2%E8%A9%A6%E5%88%86%E4%BA%AB-96e07bb15169)
## Javascript Interview Questions
1. Explain `Hoisting` in javascript.
>Hoisting is a default behaviour of javascript where **all the variable and function declarations are moved on top.**
>
>**Variable initializations(賦值) are not hoisted, only variable declarations(宣告) are hoisted**
>
>To avoid hoisting, you can run javascript in strict mode by using `use strict` on top of the code
```
"use strict";
x = 23; // Gives an error since 'x' is not declared
var x;
```
2. Explain `Implicit Type Coercion` in javascript.
>Implicit type coercion in javascript is **automatic conversion of value from one data type to another.**
> When a number is added to a string, the number type is always converted to the string type.
```
var x = 3;
var y = "3";
x + y // Returns "33"
```
>Using **‘ - ‘ operator is that, a string is converted to a number** and then subtraction takes place.
```
var x = 3;
var y = "3";
x - y //Returns 0 since the variable y (string type) is converted to a number type
```
3. Is javascript a `statically typed` or a `dynamically typed` language?
>JavaScript is a **dynamically typed** language.
>
>In a `dynamically typed` language, the type of a variable is checked during **run-time(the time at which the executable code is started running.)**.
>
>In a `statically typed` language, where the type of a variable is checked during **compile-time(source code is converted into an executable code)**.

4. What is `NaN` property in JavaScript?
>`NaN` property represents **Not-a-Number** value. It indicates a value which is not a legal number.
>
>`typeof` of a NaN will return a **Number**.
>
>To check if a value is NaN, we use the `isNaN()` function,
5. Explain `passed by value` and `passed by reference`.
>In JavaScript
>
> - **`primitive data type`(ex: Number、Boolen、String...)** are **passed by value**
> - **`non-primitive data types`(ex: Object、Array...)** are **passed by reference**.
6. What is an `Immediately Invoked Function(IIFE)` in JavaScript?
>a function that runs as soon as it is defined.
```
(function(){
// Do something;
})();
```
7. Explain `this` keyword.
>The `this` keyword **refers to the object that the function is a property of.**
>
>The value of `this` keyword will **always depend on the object that is invoking the function.**
8. Explain `call()`, `apply()` and, `bind()` methods.
>`call()` method **allows an object to use the method (function) of another object, and it accepts arguments.**
```
function saySomething(message){
return this.name + " is " + message;
}
var person4 = {name: "John"};
saySomething.call(person4, "awesome"); // Returns "John is awesome"
```
>`apply()` is similar to the `call()` method. The only difference is that, `call()` method takes arguments separately whereas, **`apply()` method takes arguments as an array.**
```
function saySomething(message){
return this.name + " is " + message;
}
var person4 = {name: "John"};
saySomething.apply(person4, ["awesome"]);
```
>`bind()` method **returns a new function, where the value of `this` keyword will be bound to the owner object, which is provided as a parameter.**
```
var bikeDetails = {
displayDetails: function(registrationNumber,brandName){
return this.name+ " , "+ "bike details: "+ registrationNumber + " , " + brandName;
}
}
var person1 = {name: "Vivek"};
var detailsOfPerson1 = bikeDetails.displayDetails.bind(person1, "TS0122", "Bullet");
// Binds the displayDetails function to the person1 object
detailsOfPerson1();
// Returns Vivek, bike details: TS0452, Thunderbird
```
9. What is currying in JavaScript?
>Currying is an advanced technique to **transform a function of arguments n, to n functions of one or less arguments.**
>
>if we have a function `f(a,b)` , then the function after currying, will be transformed to `f(a)(b)`.
```
function add (a) {
return function(b){
return a + b;
}
}
add(3)(4)
```
10. Explain `Closures` in JavaScript.
>This ability of **a function to store a variable for further reference even after it is executed, is called Closure.**
```
function randomFunc(){
var obj1 = {name:"Vivian", age:45};
return function(){
console.log(obj1.name + " is "+ "awesome"); // Has access to obj1 even when the randomFunc function is executed
}
}
var initialiseClosure = randomFunc(); // Returns a function
initialiseClosure();
```
11. What are object prototypes?
>**A prototype is a blueprint of an object.**
>
>On top of the chain is `Object.prototype`. Every prototype inherits properties and methods from the `Object.prototype`.
12. What are `callbacks`?
>**Functions that are used as an argument to another function** are called **callback functions**.
```
function divideByHalf(sum){
console.log(Math.floor(sum / 2));
}
function multiplyBy2(sum){
console.log(sum * 2);
}
function operationOnSum(num1,num2,operation){
var sum = num1 + num2;
operation(sum); //傳入的operation決定要用什麼函式計算
}
operationOnSum(3, 3, divideByHalf); // Outputs 3
operationOnSum(5, 5, multiplyBy2); // Outputs 20
```
13. What is `memoization`?
>Memoization is a form of **caching(快取)** where the **return value of a function is cached based on its parameters.** **If the parameter of that function is not changed, the cached version of the function is returned.**
>Although using memoization saves time, it **results in larger consumption of memory** since we are storing all the computed results.
```
function memoizedAddTo256(){
var cache = {};
return function(num){
if(num in cache){
console.log("cached value");
return cache[num]
}
else{
cache[num] = num + 256;
return cache[num];
}
}
}
var memoizedFunc = memoizedAddTo256();
memoizedFunc(20); // Normal return
memoizedFunc(20); // Cached return
```
14. What is the use of a `constructor` function in javascript?
>Constructor functions are used to **create objects** in javascript.
>
>If we want to create multiple objects having **similar properties and methods**, constructor functions are used.
>
>**Name of a constructor function should always be written in Pascal Notation(大寫開頭): every word should start with a capital letter.**
```
function Person(name,age,gender){
this.name = name;
this.age = age;
this.gender = gender;
}
var person1 = new Person("Vivek", 76, "male");
console.log(person1);
var person2 = new Person("Courtney", 34, "female");
console.log(person2);
```
15. What are `classes` in javascript?
>Introduced in the ES6 version, **classes are nothing but syntactic sugars(語法糖) for constructor functions.**
```
// Before ES6 version, using constructor functions
function Student(name,rollNumber,grade,section){
this.name = name;
this.rollNumber = rollNumber;
this.grade = grade;
this.section = section;
}
// Way to add methods to a constructor function
Student.prototype.getDetails = function(){
return 'Name: ${this.name}, Roll no: ${this.rollNumber}, Grade: ${this.grade}, Section:${this.section}';
}
let student1 = new Student("Vivek", 354, "6th", "A");
student1.getDetails();
// Returns Name: Vivek, Roll no:354, Grade: 6th, Section:A
// ES6 version classes
class Student{
constructor(name,rollNumber,grade,section){
this.name = name;
this.rollNumber = rollNumber;
this.grade = grade;
this.section = section;
}
// Methods can be directly added inside the class
getDetails(){
return 'Name: ${this.name}, Roll no: ${this.rollNumber}, Grade:${this.grade}, Section:${this.section}';
}
}
let student2 = new Student("Garry", 673, "7th", "C");
student2.getDetails();
// Returns Name: Garry, Roll no:673, Grade: 7th, Section:C
```
>Key points to remember about classes:
>
> - **Unlike functions, classes are not hoisted.** A class cannot be used before it is declared.
> - A class can **inherit** properties and methods from other classes **by using the `extend` keyword.**
> - All the syntaxes inside the class **must follow the strict mode(‘use strict’)** of javascript. Error will be thrown if the strict mode rules are not followed.
16. What's is `TDZ(Temporal Dead Zone)`?
>let 和 const 宣告的變數一樣會被 `hoist` 提升到 scope 的最上方,但和 var 不一樣的是,**在變數宣告之前存取變數會造成 ReferenceError 錯誤,因為用 let 和 const 宣告的變數,在程式執行到變數宣告的地方之前,都會暫時被存放在所謂的 Temporal Dead Zone (暫時性死區),不能被存取。**
```
function foo() {
// 會造成程式錯誤 ReferenceError
console.log(bar);
let bar = 101;
}
```
* [Javascript Interview Questions](https://www.interviewbit.com/javascript-interview-questions/#javscript-data-types)