# Interview question javascript 2.0
###### tags: `interview` `question` `javascript` `algorithms`
### Cần xem lại các câu có dấu ***
## 1. Promise
```javascript!
/*
Promise là một lời hứa, nó có 3 trạng thái là chờ đợi, thành công và thất bại
Để cho dễ hiểu thì tưởng tượng bạn được người yêu của bạn hứa sẽ mua cho bạn điện thoại iphone 14 promax
- Bạn sẽ CHỜ tin mừng từ người yêu của bạn => Trạng thái pending
- Khi người yêu bạn giữ đúng lời hứa và mua cho bạn 1 cái iphone mới => Trạng thái thành công (resolve)
- Khi người yêu bạn bị xếp trừ lương và không còn đủ tiền mua cho bạn => Trạng thái thất bại (reject)
Qua đó thì rút ra được công thức của Promise:
new Promise(function(resolve,reject)){
resolve
reject
}
Promise sẽ trả về 3 phương thức:
- then (onFullFilled,onReject): phương thức này khi promise trả về thành công
- catch (onReject): phương thức này khi promise trả về thất bại
- finally(): phương thức này dù thành công hay thất bại cũng sẽ chạy nó khi kết thúc 2 phương thức trên
Lưu ý: bên trong tất cả các phương thức trên phải có ít nhất 1 hàm (function) để xử lí
.then(function(){
//code here
})
.catch(function(){
//code here
})
.finally(function(){
//code here
})
*/
let iphone = true;
function makePromise(iphone) {
return new Promise(function (resolve, reject) {
setTimeout(() => {
if (iphone) {
resolve("Have new iphone");
} else {
reject("Dont have new iphone");
}
}, 3000);
});
}
let haveIphone = makePromise(false);
haveIphone
.then((success) => console.log(success))
.catch((err) => {
console.log(err);
})
.finally(() => {
console.log("Dont worry about it");
});
```
## 2. Promise.all & promise.race
```javascript=
// Promise all là trả về danh sách promise hiện hành,
// nó sẽ đợi toàn bộ chạy xong rồi nó mới trả kết quả.
// Nó sẽ trả về một mảng khi tất cả đều resolve,
// hoặc là reject khi một trong những promise lỗi.
// Lúc đó nó sẽ dừng hẳn và trả kết quả liền.
function makePromise(timer = 1000, str) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(str);
}, timer);
});
}
const timer1 = makePromise(1000, "First");
const time2 = makePromise(2000, "Second");
// const [a, b] = await Promise.all([timer1, time2]);
// console.log(a, b);
// và Promise.all cũng thật sự trả về Promise nên thành ra có thể .then .catch
const timerTotal = Promise.all([timer1, time2]).then((data) => {
console.log(data);
});
/*
Promise.race là phương thức sẽ trả về promise nào có tốc độ xử lí nhanh nhất,
nó sẽ không quan tâm lỗi hay là thành công
*/
const timer3 = Promise.race([timer1, time2]).then((data) => {
console.log(data);
}); // trả về first vì first có tốc độ xử lí là 1s
```
## 3. Callback hell
```javascript=
// callback hell là một loại callback lồng callback liên tục,
// vì mong muốn kết thúc sự kiện, chức năng này mới chạy sự kiện
// chức năng tiếp theo
setTimeout(() => {
console.log("first");
setTimeout(() => {
console.log("second");
setTimeout(() => {
console.log("third");
setTimeout(() => {
console.log("fourth");
}, 1000);
}, 1000);
}, 1000);
}, 3000);
// Nghĩa là khi sau 3 giây mới được chạy second,
// rồi xong second mới chạy third...
// Để giải quyết vấn đề này thì Promise được ra đời
```
## 4. Bubble
https://codepen.io/henrylenguyen/pen/oNMvdpo
## 5. e.preventDefault() và e.target e.currentTarget
https://codepen.io/henrylenguyen/pen/NWBKoKW
## 6. Traversing
https://codepen.io/henrylenguyen/pen/bGKPLXv
## 7. Cắt đoạn
https://codepen.io/henrylenguyen/pen/rNKggWQ
## 8. DOm
https://codepen.io/henrylenguyen/pen/NWzMjVo
## 9. Unique array
https://codepen.io/henrylenguyen/pen/xxzjwzY
## 10. Slice array
https://codepen.io/henrylenguyen/pen/MWXGwex
## 11.
https://codepen.io/henrylenguyen/pen/OJEvXaV
## 12. flat icon array
https://codepen.io/henrylenguyen/pen/rNKdLNj
## 13. rest parameter
https://codepen.io/henrylenguyen/pen/QWxmWww
## 14. sao chép mảng
https://codepen.io/henrylenguyen/pen/rNKJQWz
## 15. gộp mảng
https://codepen.io/henrylenguyen/pen/RwJQeQy
## 16. so sánh mảng
https://codepen.io/henrylenguyen/pen/WNyMbdy
## 17. reverse string
https://codepen.io/henrylenguyen/pen/qBKPGev
## 18. delete object
https://codepen.io/henrylenguyen/pen/zYadbaY
## 19. Reverse string
```javascript!
function reverseString(s){
const result = [];
for(let i = s.length-1 ; i>=0;i--){
result.push(s[i]);
}
return result.join('');
}
console.log(reverseString('abcdef'));
console.log(reverseString('12345'))
```
```javascript!
fedcba
54321
```
## 20. Kết quả đoạn code sau :
```javascript!
function sayHi(){
console.log(name);
console.log(age);
var name = 'Lydia';
let age = 21;
}
sayHi()
```
Result : undefined and References error
## 21. Kết quả đoạn code sau :
```javascript!
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i, 'var'));
}
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i, 'let'))
}
```
var : 3 3 3 - let : 0 1 2
thằng var là function/ global scope. let là block scope
## 22. Kết quả đoạn code sau :
```javascript!
const shape = {
radius:10,
diameter(){
console.log(this.radius * 2);
// return this.radius * 2 - they can write like this
},
perimeter: () => console.log(2 * Math.PI * this.radius)
};
shape.diameter();
shape.perimeter()
```
```javascript
20
NaN // lí do là vì trong arrow fc ko hỗ trợ con trỏ this,
// this.radius = undefined => con số * undefined === NaN (not a number)
```
## 23. Kết quả đoạn code sau :
```javascript!
console.log(+true);
console.log(!"ICT Hà Nội")
```
```javascript!
1
false
```
## 24. Kết quả đoạn code sau :
```javascript!
const bird = {
size: 'small'
};
const mouse = {
name: 'Mickey',
small : true
}
```
```javascript!
mouse.bird.size -> ko hợp lệ
```
## 25. Kết quả đoạn code sau :
```javascript
let c = { greeting: 'Hey'};
let d;
d = c;
c.greeting = 'Hello';
console.log(d.greeting);
```
```javascript
Hello // tìm hiểu về Heap memory, stack memory,
```
## 26. Kết quả đoạn code sau :
```javascript
let a = 3;
let b = new Number(3);
let c = 3;
console.log(a==b); // ko xét kiểu dữ liệu
console.log(a===b);
console.log(b===c);
```
```javascript
true
false
false
```
Lí do
```javascript
console.log(typeof b) // object
console.log(typeof a) // number
```
## 27. Kết quả đoạn code sau : ***
```javascript=
class Chameleon{
static colorChange(newColor){
this.newColor = newColor;
return this.newColor;
}
constructor({ newColor = 'green' } = {}){
this.newColor = newColor;
}
}
const freddie = new Chameleon({newColor:'purple'});
freddie.colorChange('orange')
```
TypeError tìm hiểu về static trong js
https://freetuts.net/static-trong-javascript-5409.html
## 28. Kết quả đoạn code sau : ***
```javascript!
class Article {
static publisher = "Huy nè"
show() {
console.log(this.publisher);
// sửa thành như này sẽ chạy => console.log(this.constructor.publisher);
}
}
let a = new Article();
a.show();
```
```javascript!
undefined // static
```
## 29. Kết quả đoạn code sau : ***
```javascript=
class User {
sayHi() {
console.log("Xin chào");
}
static staticMethod() {
this.sayHi(); // sai vì ko có từ khóa static sayHi()
}
}
User.staticMethod(); // true
```
```javascript=
TypeError : this.sayHi is not a function
```
## 30. Kết quả đoạn code sau :
```javascript
let greeting;
greetgn = {} // giả sử bị lỗi đánh máy
console.log(greetgn)
```
```
{} // lí do là vì javascript tự khai báo var cho biến này nhé
// trừ chế độ use strict
```
## 31. Kết quả đoạn code sau :
```javascript!
function bark() {
console.log("wooff");
}
bark.animal = "dog";
console.log(bark.animal)
```
```javascript!
dog // về cơ bản array và function cũng là object ở dạng đặc biệt
```
## 32. Kết quả đoạn code sau :
```javascript!
function Person(firstName, lastName){
this.firstName = firstName;
this.lastName = lastName;
}
const member = new Person("Lydia","Hallie");
Person.getFullName = function(){
return `${this.firstName} ${this.lastName}`;
};
console.log(member.getFullName());
```
```javascript!
TypeError: member.getFullName is not a function
```
Fix :
```javascript!
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
Person.prototype.getFullName = function() {
return `${this.firstName} ${this.lastName}`;
};
const member = new Person("Lydia", "Hallie");
console.log(member.getFullName()); // Output: Lydia Hallie
```
another way by `class` keyword
```javascript!
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
}
const member = new Person("Lydia", "Hallie");
console.log(member.getFullName()); // Output: Lydia Hallie
```
## 33. Kết quả đoạn code sau :
```javascript!
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
const lydia = new Person("Lydia", "Hallie");
const sarah = Person("sarah", "smith");
console.log(lydia);
console.log(sarah);
```
Đáp án của công ty
```javascript
Person {firstName: 'Lydia', lastName: 'Hallie'}
undefined
```
Đáp án chạy thử
```javascript
caught TypeError: Cannot set properties of undefined (setting 'firstName')
```
## 34. Kết quả đoạn code sau :
```javascript!
function sum(a, b) {
return a + b;
}
sum(1, "2");
```
```javascript!
12
```
## 35. Tất cả các object đều có prototype ?
Đúng
## 36. Kết quả đoạn code sau
```javascript
let number = 0;
console.log(number++);
console.log(++number);
console.log(number)
```
```
0
2
2
```
## 37. Câu tào lao ai đâu code như này
```javascript!
function getPersonInfo(one,two,three){
console.log(one);
console.log(two);
console.log(three)
}
const person = 'Lydia';
const age = 21;
getPersonInfo`ahuy huy ${person} is ${age} years old`
```
```javascript!
> (3) ['ahuy huy ',' is ',' years old', raw: Array(3)] // để ý chỗ space nhé
Lydia
21
```
## 38. Câu này hay
```javascript
function checkAge(data) {
if (data == { age: 18 }) {
console.log("You are an adult");
} else if (data == { age: 18 }) {
console.log("You are still an adult");
} else {
console.log("Hmm.. you dont have an age i guess");
}
}
checkAge({ age: 18 });
```
```javascript!
Hmm.. you dont have an age i guess
```
Giải thích : liên quan đến vùng nhớ heap của object, lưu địa chỉ bên heap mmr
## 39. Câu này hay
```javascript
function getAge(...args){
console.log(typeof args);
}
getAge(21);
```
```
object // object nhé
```
## 40. Câu này hay
```javascript!
function getAge(){
"use strict";
age = 21; // khi ko ở chế độ use strict, nó sẽ tự gắn var vào biến nhé
console.log(age)
}
getAge();
```
```javascript!
caught ReferenceError: age is not defined
```
## 41. Câu này hay
```javascript!
const sum = eval("10*10+5")
console.log(sum)
```
```javascript!
105 // hàm eval tính toán như toán học bth thôi nhé
```
Soạn tiếp
https://codepen.io/henrylenguyen/pen/YzRwLRW?editors=0012
### 42. bỏ dubplicate trong value string
:::spoiler
```javascript!
function removeDuplicates(inputString) {
const valuesArray = inputString.split(",");
const uniqueValues = [...new Set(valuesArray)];
const resultString = uniqueValues.join(",");
return resultString;
}
```
:::
### 43. Đáp án
```javascript!
var a = 10;
function getA() {
var a;
console.log(a / 2)
return a = 20
}
console.log(getA())
```
:::spoiler
NaN - do khai báo lại biến, re-allocate lại bộ nhớ
:::
### 44. Đáp án
```javascript!
var user = {
name: "huy",
getName() {
return this.name
}
}
const newUser = new user.getName
console.log(newUser)
```
:::spoiler
user.getName is not a constructor
:::