From 6f07661701856e007007a2927f7082c18ad9fcb1 Mon Sep 17 00:00:00 2001
From: Samaha Musthafa
@@ -10219,7 +10225,9 @@ console.log('Third line')
When JavaScript encounters a line break without a semicolon, the JavaScript parser will automatically add a semicolon based on a set of rules called `Automatic Semicolon Insertion` which determines whether line break as end of statement or not to insert semicolon. But it does not assume a semicolon before square brackets [...]. So the first two lines considered as a single statement as below.
```javascript
-console.log('First line')['a', 'b', 'c'].forEach((element) => console.log(element))
+console
+ .log("First line")
+ [("a", "b", "c")].forEach((element) => console.log(element));
```
Hence, there will be **cannot read properties of undefined** error while applying the array square bracket on log function.
@@ -10238,21 +10246,37 @@ Hence, there will be **cannot read properties of undefined** error while applyin
```javascript
-const HEX_ALPHABET = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"];
+const HEX_ALPHABET = [
+ "0",
+ "1",
+ "2",
+ "3",
+ "4",
+ "5",
+ "6",
+ "7",
+ "8",
+ "9",
+ "a",
+ "b",
+ "c",
+ "d",
+ "e",
+ "f",
+];
const HEX_PREFIX = "#";
const HEX_LENGTH = 6;
function generateRandomHex() {
- let randomHex = "";
+ let randomHex = "";
- for(let i = 0; i < HEX_LENGTH; i++) {
- const randomIndex = Math.floor(Math.random() * HEX_ALPHABET.length);
- randomHex += HEX_ALPHABET[randomIndex];
- }
+ for (let i = 0; i < HEX_LENGTH; i++) {
+ const randomIndex = Math.floor(Math.random() * HEX_ALPHABET.length);
+ randomHex += HEX_ALPHABET[randomIndex];
+ }
- return HEX_PREFIX + randomHex;
+ return HEX_PREFIX + randomHex;
}
-
```
-```javascript
+```javascript
const HEX_PREFIX = "#";
const HEX_RADIX = 16;
const HEX_LENGTH = 6;
function generateRandomHex() {
- return HEX_PREFIX + Math.floor(Math.random() * 0xffffff).toString(HEX_RADIX).padStart(HEX_LENGTH, "0");
-}
+ return (
+ HEX_PREFIX +
+ Math.floor(Math.random() * 0xffffff)
+ .toString(HEX_RADIX)
+ .padStart(HEX_LENGTH, "0")
+ );
+}
```
@@ -10326,10 +10355,10 @@ numbers.sort();
console.log(numbers);
```
-- 1: [11, 18, 23, 25, 31, 33, 200]
-- 2: [11, 18, 200, 23, 25, 31, 33]
-- 3: [11, 25, 31, 23, 33, 18, 200]
-- 4: Cannot sort numbers
+- 1: [11, 18, 23, 25, 31, 33, 200]
+- 2: [11, 18, 200, 23, 25, 31, 33]
+- 3: [11, 25, 31, 23, 33, 18, 200]
+- 4: Cannot sort numbers
@@ -10345,6 +10374,7 @@ console.log(numbers);
```
**Note:** Sort() method changes the original array.
+
##### Answer: 4
+
When the JavaScript engine parses the above code, the first two statements are asynchronous which will be executed later and third statement is synchronous statement which will be moved to callstack, executed and prints the number 3 in the console. Next, Promise is native in ES6 and it will be moved to Job queue which has high priority than callback queue in the execution order. At last, since setTimeout is part of WebAPI the callback function moved to callback queue and executed. Hence, you will see number 2 printed first followed by 1.
+
##### Answer: 4
+
IIFE(Immediately Invoked Function Expression) is just like any other function expression which won't be hoisted. Hence, there will be a reference error for message call.
The behavior would be the same with below function expression of message1,
+
```javascript
console.log(name);
console.log(message());
@@ -10407,6 +10443,7 @@ var message = function () {
console.log('Hello John: Welcome');
});
```
+
##### Answer: 3
+
As part of hoisting, initially JavaScript Engine or compiler will store first function in heap memory but later rewrite or replaces with redefined function content.
+
##### Answer: 3
+
Due to hositing feature, the variables declared with `var` will have `undefined` value in the creation phase so the outer variable `currentCity` will get same `undefined` value. But after few lines of code JavaScript engine found a new function call(`changeCurrentCity()`) to update the current city with `var` re-declaration. Since each function call will create a new execution context, the same variable will have `undefined` value before the declaration and new value(`Singapore`) after the declarion. Hence, the value `undefined` print first followed by new value `Singapore` in the execution phase.
+
##### Answer: 1
+
Each context(global or functional) has it's own variable environment and the callstack of variables in a LIFO order. So you can see the message variable value from second, first functions in an order followed by global context message variable value at the end.
+
##### Answer: 1
+
The function call `functionOne` is not going to be part of scope chain and it has it's own execution context with the enclosed variable environment. i.e, It won't be accessed from global context. Hence, there will be an error while invoking the function as `functionOne is not defined`.
+
##### Answer: 4
+
`this` keyword is dynamic scoped but not lexically scoped . In other words, it doesn't matter where `this` has been written but how it has been invoked really matter. In the above code snippet, the `user` object invokes `eat` function so `this` keyword refers to `user` object but `eatFruit` has been invoked by `eat` function and `this` will have default `Window` object.
The above pit fall fixed by three ways,
1. In ES6, the arrow function will make `this` keyword as lexically scoped. Since the surrounding object of `this` object is `user` object, the `eatFruit` function will contain `user` object for `this` object.
+
```javascript
const user = {
- name: 'John',
+ name: "John",
eat() {
console.log(this);
var eatFruit = () => {
console.log(this);
- }
- eatFruit()
- }
-}
+ };
+ eatFruit();
+ },
+};
user.eat();
```
+
The next two solutions have been used before ES6 introduced.
2. It is possible create a reference of `this` into a separate variable and use that new variable inplace of `this` keyword inside `eatFruit` function. This is a common practice in jQuery and AngularJS before ES6 introduced.
+
```javascript
const user = {
- name: 'John',
+ name: "John",
eat() {
console.log(this);
var self = this;
var eatFruit = () => {
console.log(self);
- }
- eatFruit()
- }
-}
+ };
+ eatFruit();
+ },
+};
user.eat();
```
+
3. The `eatFruit` function can bind explicitly with `this` keyword where it refers `Window` object.
+
```javascript
const user = {
- name: 'John',
+ name: "John",
eat() {
console.log(this);
- var eatFruit = function() {
+ var eatFruit = function () {
console.log(this);
- }
- return eatFruit.bind(this)
- }
-}
+ };
+ return eatFruit.bind(this);
+ },
+};
user.eat()();
```
+
##### Answer: 3
+
In JavaScript, primitives are immutable i.e. there is no way to change a primitive value once it gets created. So when you try to update the string's first character, there is no change in the string value and prints the same initial value `Hello World!`. Whereas in the later example, the concatenated value is re-assigned to the same variable which will result into creation of new memory block with the reference pointing to `John Smith` value and the old memory block value(`John`) will be garbage collected.
+
##### Answer: 2
+
In JavaScript, the variables such as objects, arrays and functions comes under pass by reference. When you try to compare two objects with same content, it is going to compare memory address or reference of those variables. These variables always create separate memory blocks hence the comparison is always going to return false value.
+
##### Answer: 3
+
The variable `message` is still treated as closure(since it has been used in inner function) eventhough it has been declared after setTimeout function. The function with in setTimeout function will be sent to WebAPI and the variable declaration executed with in 5 seconds with the assigned value. Hence, the text declared for the variable will be displayed.
+
##### Answer: 1
+
Eventhough both variables `a` and `b` refer a number value, the first declaration is based on constructor function and the type of the variable is going to be `object` type. Whereas the second declaration is primitive assignment with a number and the type is `number` type. Hence, the equality operator `===` will output `false` value.
+
##### Answer: 2
+
Eventhough the above function returns the same result for the same arguments(input) that are passed in the function, the `console.log()` statement causes a function to have side effects because it affects the state of an external code. i.e, the `console` object's state and depends on it to perform the job. Hence, the above function considered as impure function.
+
##### Answer: 3
+
The above promises settled at the same time but one of them resolved and other one rejected. When you use `.all` method on these promises, the result will be short circuted by throwing an error due to rejection in second promise. But If you use `.allSettled` method then result of both the promises will be returned irrespective of resolved or rejected promise status without throwing any error.
```javascript
-Promise.allSettled([promiseOne, promiseTwo]).then(data => console.log(data));
+Promise.allSettled([promiseOne, promiseTwo]).then((data) => console.log(data));
```
+
##### Answer: 3
+
If you put `setTimeout` and `setInterval` methods inside the try clause and an exception is thrown, the catch clause will not catch any of them. This is because the try...catch statement works synchronously, and the function in the above code is executed asynchronously after a certain period of time. Hence, you will see runtime exception without catching the error. To resolve this issue, you have to put the try...catch block inside the function as below,
```javascript
setTimeout(() => {
- try {
- console.log('try block');
- throw new Error(`An exception is thrown`)
- } catch(err) {
- console.log('Error: ', err);
- }
-
- }, 1000);
+ try {
+ console.log("try block");
+ throw new Error(`An exception is thrown`);
+ } catch (err) {
+ console.log("Error: ", err);
+ }
+}, 1000);
```
+
You can use `.catch()` function in promises to avoid these issues with asynchronous code.
+
##### Answer: 2
+
The variable "a" declared inside "if" has block scope and does not affect the value of the outer "a" variable.
+
##### Answer: 4
+
The length of the array 'arr' has been set to 0, so the array becomes empty.
+
Answer
Solution 2 (One-liner)
Answer
Answer
Answer
Answer
Answer
Answer
Answer
Answer
Answer
Answer
Answer
Answer
Answer
Answer
Answer
Answer
Answer
Answer
+ +##### Answer: 4 + +The function `printHello` is hoisted to the top of the global scope and prints "Hello" to the console. Even `printMessage` function is hoisted, but it is lifted to the local scope(in "printHello") it was declared in. That is the reason you will endup with reference error for second function call. + +But if the second function is invoked in the first function itself, there won't be any reference error. + +```javascript +printHello(); + +function printHello() { + printMessage(); + console.log('Hello') + + function printMessage() { + console.log("Good day") + } +} +``` + +
++ +##### Answer: 1 + +Even though there is a timer of 5 seconds supplied to `setTimeout` callback, it won't get executed until the main thread is free and finished executing the remaining part of the code. In this example, the remaining code(while loop) takes 10seconds to finish it's execution. In the mean time, the callback will be stored in callback queue upon completion of its 5 seconds timer. After 10 seconds, the callback will be moved to callstack because the callstack is empty by poping out global execution context. + +
+
+
+
+
+
jrTwtu+5=7uq?9V0;mf~QEsWtls@KGmA
diff --git a/images/collab/greatfrontend-js-banner4x.png b/images/collab/greatfrontend-js-banner4x.png
new file mode 100644
index 0000000000000000000000000000000000000000..18be67268af5966bffdb46eaffec1f5b42b8c762
GIT binary patch
literal 806174
zcmWifdpy(MAID4Il6xhQ+eDFam-}UflH4k}Ulx*bN$z(mDtB@xmnBJZ8Ofc^edIE^
zO>V<53^Owun|*%${y2~GIPbsCKkxH?pV#a8j(=!o$i*(me&WOlE~EPfk58Q7&OLF0
z#q#W#f05UY{LlVvY_IRz`ky!
D{|y$h_7@p$N@x2p*G
zVv2a(t12GcPd}LFc1!+!9PfQ
+!CvIw7XLO?>X4m%q*7-*@{QUOFtnt!Gpk8_x7H9P<
zsU=+}+=*`&G=QhLo1F#=rlzr+%+O}7VhSog6($FX3tir6Mp&au2dPpFyelg9ze{^D
zLJ?8LdjB}H)Ndl<9rT%!QwBA%_agXiEUS+Shh|RP2z59U_Qh&1d-EdtQnW&KogrG{
zfvX69KqQ63iMO=rpEBPss
*rQaa7*Z2d
z9v|`NV(p04e=<#`VI*m_EwRmUF|G=|L2|iAnqpaJO2WEd@&{~0q|ctjp&`Lc2Qqx1
zs
)-=43~wmZ?~*R
z)mO