Javascript/Dive Into JavaScript - Advanced Concepts.md
... ...
@@ -0,0 +1,297 @@
1
+https://blog.bitsrc.io/javascript-under-the-hood-advanced-concepts-developers-should-know-a89ddbb11228
2
+
3
+# Dive Into JavaScript: Advanced Concepts | Bits and Pieces
4
+JavaScript Under The Hood: Advanced Concepts Developers Should Know
5
+-------------------------------------------------------------------
6
+
7
+The art of programming is the skill of controlling complexity.
8
+--------------------------------------------------------------
9
+
10
+[
11
+
12
+![Noor Ahmed](https://miro.medium.com/v2/resize:fill:88:88/1*p53Smv8cq2h9bizJ335xZQ@2x.jpeg)
13
+
14
+
15
+
16
+](https://medium.com/@noor882?source=post_page---byline--a89ddbb11228--------------------------------)
17
+
18
+[
19
+
20
+![Bits and Pieces](https://miro.medium.com/v2/resize:fill:48:48/1*7jl7ls1SeoNkYU742b9j1Q.png)
21
+
22
+
23
+
24
+](https://blog.bitsrc.io/?source=post_page---byline--a89ddbb11228--------------------------------)
25
+
26
+Have you ever wondered what happens inside the JavaScript engine when you execute your code?
27
+
28
+[www.clipartkey.com](http://www.clipartkey.com/)
29
+
30
+It’s pretty interesting!
31
+
32
+Currently, it’s 2022. JavaScript has taken over the internet. People are swarming to libraries and frameworks searching for helpful anything — Not understanding the **fundamentals** of JavaScript.
33
+
34
+In addition, they claim that JavaScript sucks. What the hell?
35
+
36
+> When I first decided to work using JavaScript, I had a lot of questions and couldn’t figure out why my code behaved the way it did. It was challenging to handle undefined errors or identify the scope of a variable.
37
+
38
+In this blog, I’ll walk you through your code’s journey, illustrating the inner workings of advanced concepts like **scope chain, hoisting, asynchronous, and function execution** concerning **execution context** and the **call stack**.
39
+
40
+All subtopics are related, so please don’t skip them — grab a cup of coffee, and enjoy reading!.
41
+
42
+The first thing that happens inside the engine
43
+----------------------------------------------
44
+
45
+![](https://miro.medium.com/v2/resize:fit:720/format:webp/0*obv7emtEI6mqxwS0.png)
46
+
47
+Your code isn’t magic. Someone else wrote a program to translate it for the computer.
48
+
49
+When you write a program, a **syntax parser** reads your code and then the **compiler** translates it into computer instructions(_a lower-level language)._
50
+
51
+Take a look at this simple code:
52
+
53
+![](https://miro.medium.com/v2/resize:fit:640/format:webp/1*SltyyUJQBPlNkggLTVdb6w.png)
54
+
55
+Where you write your code and what surrounds it is crucial! The area of the code you are looking at physically is the **lexical environment.**
56
+
57
+In the above example, I would say the variable “**greetings**” sits **lexically** inside the function **sayHello.**
58
+
59
+It sounds funny, but not every programming language is like that. In JS, however, the **compiler** that converts your code cares about where you put things. And based on it, decide where your code will sit in the memory and interact.
60
+
61
+So there are multiple **lexical environments**, but one that is being executed is handled by **the execution context** — _a context in which javascript code is running._
62
+
63
+**The Global Execution Context**
64
+--------------------------------
65
+
66
+When the compiler first looks at your code, it asks the JS engine to create a **global execution context** for you.
67
+
68
+![](https://miro.medium.com/v2/resize:fit:640/format:webp/1*fxHMh8B5p_DLRVFh6Cm7Dg.png)
69
+
70
+The following duties are carried out:
71
+
72
+> _• Create a_ **_Memory Heap_** _to keep all variables and functions at a global level_
73
+>
74
+> _• Create a_ **_Global Object_** _and “_**this**_” keyword_
75
+
76
+The location of “**_this”_** depends on where your code is running. In the browser, for example, it points to **windows** objects. Nodejs, for example, will point to a different global object.
77
+
78
+![](https://miro.medium.com/v2/resize:fit:720/format:webp/1*ye0nLV16OGET8NGH9aNn-g.png)
79
+
80
+“**this**” keyword points to a window object in the chrome.
81
+
82
+Before proceeding with the code execution, it is vital to grasp the **hoisting.** And for that, we need to look at the **memory allocation.**
83
+
84
+Execution Context: Hoisting
85
+---------------------------
86
+
87
+We are frequently baffled when it comes to hoisting. One of the most fundamental JS concepts to grasp and among the interviewer’s top questions.
88
+
89
+index.js:
90
+```js
91
+sayHello();
92
+console.log(myVar);
93
+
94
+function sayHello() {
95
+ console.log('Hello!');
96
+}
97
+
98
+var myVar = 'hello again';
99
+```
100
+
101
+Console output:
102
+```
103
+Console was cleared
104
+Hello!
105
+undefined
106
+```
107
+
108
+Take a look at the code above. We ran our code before the declaration and, sayHello() returned “**Hello!**” whereas myVar logged **undefined**?
109
+
110
+Why is that?
111
+
112
+We need to look at the **execution context creation phase**. When your **parser** runs through your code, it recognizes where you have created the variables and functions, and so it sets up the **memory space** for them — _Which explains why you can access functions and variables before they are_ **_declared_**.
113
+
114
+However, keep in mind that only **declarations are hoisted** by JavaScript, **not initializations**! That is, initialization does not occur until the appropriate line of code is executed. Until then, when declared with “**var**,” the variable is set to “**undefined**” (_let and const are hoisted but are_ **_not initialized_** _with a_ **_default value_**). Function declarations are hoisted in the same way, but **function expressions are not**.
115
+
116
+index.js:
117
+```js
118
+foo();
119
+console.log(myVar);
120
+
121
+bar(); // cannot access uninitialized variable
122
+console.log(myVarTwo);
123
+
124
+function foo() {
125
+ console.log('foo');
126
+}
127
+
128
+const bar = () => {
129
+ console.log('bar');
130
+};
131
+
132
+var myVar = 'myVar';
133
+const myVarTwo = 'myVarTwo'; // cannot access uninitialized variable
134
+
135
+```
136
+
137
+Console output:
138
+```
139
+Console was cleared
140
+foo
141
+undefined
142
+index.js:3
143
+Error: Cannot access 'bar' before initialization
144
+```
145
+
146
+only variables with var and function declarations are initialized
147
+
148
+_Now that your code has been_ **_compiled_** _and_ **_memory space_** _has been set up, it’s time to_ **_execute it_**.
149
+
150
+Execution context — function invocation and the Call Stack
151
+----------------------------------------------------------
152
+
153
+**_When your code is executed line by line…_**
154
+
155
+![](https://miro.medium.com/v2/resize:fit:640/format:webp/1*X7GEvMs5F-kRAaYz8-mahQ.png)
156
+
157
+As your code is executed, the variable **favorite** is assigned to **“C#”**, and when it encounters **favLanguage()**, it says, “_Ahh, I need to invoke this function_.”
158
+
159
+It creates a **new execution context** and puts it on top of the **call stack —** _like an actual stack in data structures that follows the_ **_Last In First Out (LIFO) principle._** It has its **creation and execution phases**, where **memory space** for any variables or function calls inside side **favLanguage()** is assigned.
160
+
161
+It then runs each line inside **favLanguage()**. As it does so, a **favorite** is assigned to “**javascript**”, and **otherLanguage()** is invoked, which creates another execution context for it and places it at the top of the **call stack**.
162
+
163
+![](https://miro.medium.com/v2/resize:fit:640/format:webp/1*vhfluQjQLg5OsmNHgpmwYQ.png)
164
+the black part in the picture is the local variable environment
165
+
166
+Here’s how the above explanation looks in real-time!
167
+
168
+![](https://miro.medium.com/v2/resize:fit:640/format:webp/1*ibOTsu2br15Yw6vxCunLaQ.gif)
169
+[Loupe](http://latentflip.com/loupe/?code=CmZ1bmN0aW9uIG90aGVyTGFuZ3VhZ2UoKXsKICAgIGxldCBmYXZvcml0ZTsKICAgIAogICAgY29uc29sZS5sb2coImNhbGxlZCBmcm9tIG90aGVyTGFuZ3VhZ2UiKTsKfQoKZnVuY3Rpb24gZmF2TGFuZ3VhZ2UoKXsKICAgIGxldCBmYXZvcml0ZSA9ICJKYXZhc2NyaXB0IjsgCiAgICBvdGhlckxhbmd1YWdlKCk7Cn0KCiBjb25zdCBmYXZvcml0ZSA9ICJDIyIKIGZhdkxhbmd1YWdlKCk7%21%21%21)
170
+
171
+> Even though "favorite" is declared 3 times, they are unique and don't touch each other as they exist in their execution context within its variable environment.
172
+
173
+
174
+**_Quick note_**_:_ When a function completes its execution, JS immediately freezes and **garbage-collects** the **memory** associated with it to **prevent memory leaks**, unless you’re using **closures**, in which case it will only release the memory once all of its **dependant functions** have been removed from the call stack.
175
+
176
+Execution Context: Scope Chain
177
+------------------------------
178
+
179
+**_How does a function access variables outside of its execution context?_**
180
+
181
+In JavaScript, the scope goes from outer to inner. This means that variables declared in the outer scope can be accessed in all inner scope, not vice versa. This entire notion is called a **scope chain**…!
182
+
183
+**What do you anticipate console.log (sport) to return in the code below?**
184
+
185
+index.js:
186
+```js
187
+function favoriteSport() {
188
+ console.log(sport);
189
+}
190
+
191
+function otherSport() {
192
+ const sport = 'volleyball';
193
+ favoriteSport();
194
+}
195
+
196
+const sport = 'basketball';
197
+otherSport();
198
+```
199
+
200
+Console output:
201
+```
202
+Console was cleared
203
+basketball
204
+```
205
+
206
+guess the answer before looking at the console in “Preview”
207
+
208
+I hope you said “basketball”. As we already know when **otherSport()** ran, an execution context was generated, triggering **favoriteSport()**, which likewise produced another execution context. When **console.log (sport)** was run, it attempted to locate the variable declaration in the **favoriteSport** function.
209
+
210
+Still, when it couldn’t, it examined the outside reference and went hunting for the variables someplace **down the call stack**. And the **external reference** point is **determined** by where your function is **lexically situated**.
211
+
212
+![](https://miro.medium.com/v2/resize:fit:720/format:webp/1*u6QIfpDmx9HfeAWQtfqIlA.png)
213
+
214
+For example, **favoriteSport() is lexically positioned not within function** **otherSport** but at the global level. As a result, its **external environment** is **global**, and it discovered “**sport**” in the **global execution context, hence logging “basketball”**
215
+
216
+> Here is a bit of fun exercise for you guys. What do you think console.log will return and why? Explain the code execution or draw a scope chain like the above. Let me know in the comments.
217
+
218
+![](https://miro.medium.com/v2/resize:fit:640/format:webp/1*H0dXpkn_gF9Rs-Kj2CKc8Q.png)
219
+
220
+JS fascinatingly handles asynchronous tasks!
221
+--------------------------------------------
222
+
223
+I hope this does not surprise you, but Javascript is **_NOT_** **asynchronous** but **synchronous, single-threaded language**(_one task at a time). Y_ou can, however, manipulate JavaScript to behave **asynchronously**. It’s not baked in, but it’s feasible!. Let’s have a peek.
224
+
225
+index.js:
226
+```js
227
+const greeting = () => {
228
+ console.log('hi!');
229
+};
230
+
231
+greeting();
232
+
233
+setTimeout(function wakeup() {
234
+ console.log("I'm awake!");
235
+}, 1000);
236
+
237
+console.log('hi again!');
238
+```
239
+
240
+Console output:
241
+```
242
+Console was cleared
243
+hi!
244
+hi again!
245
+I'm awake!
246
+```
247
+
248
+As you can see in the preceding code, it logged “**hi,**” **hi again!**,” and “**I’m awake**” in that sequence; however, given what we know so far, it can’t be using a call stack as functions are handled synchronously. Then what?. This is where the **Javascript runtime** comes in.
249
+
250
+![](https://miro.medium.com/v2/resize:fit:640/format:webp/0*76gENMS0v5rYgfU9.png)
251
+
252
+taken from [blo](https://kishorneupane.com/blog/callbacks-asynchrony-and-javascript/)g
253
+
254
+The web browser comes with a **web API** that handles **HTTP requests**, managing **dom events**, or delaying execution like **setTimeout**. We call these web APIs **asynchronous.**
255
+
256
+> So, here's how it works: We have things like a set timeout in the call stack that aren't part of JavaScript. The call stack tells the web API, "Oh, I have something that isn't mine, and I don't know what to do with it." It passes it on to the Web API.
257
+> In contrast to Web APIs, JavaScript synchronously performs tasks in the call stack. Tasks are placed in the callback queue when the web API completes its processing.The call stack will be informed that I have something for you through the Event Loop. A task from the callback queue is added to the call stack and logged as "Hi, I'm awake" when the call stack is empty.
258
+
259
+
260
+Another live visualization, this time with the Javascript runtime!
261
+
262
+![](https://miro.medium.com/v2/resize:fit:720/format:webp/1*AKmOXOPBoz0LHcIreRTzng.gif)
263
+
264
+[Loupe](http://latentflip.com/loupe/?code=JC5vbignYnV0dG9uJywgJ2NsaWNrJywgZnVuY3Rpb24gb25DbGljaygpIHsKICAgIHNldFRpbWVvdXQoZnVuY3Rpb24gdGltZXIoKSB7CiAgICAgICAgY29uc29sZS5sb2coJ1lvdSBjbGlja2VkIHRoZSBidXR0b24hJyk7ICAgIAogICAgfSwgMjAwMCk7Cn0pOwoKY29uc29sZS5sb2coIkhpISIpOwoKc2V0VGltZW91dChmdW5jdGlvbiB0aW1lb3V0KCkgewogICAgY29uc29sZS5sb2coIkNsaWNrIHRoZSBidXR0b24hIik7Cn0sIDUwMDApOwoKY29uc29sZS5sb2coIldlbGNvbWUgdG8gbG91cGUuIik7%21%21%21PGJ1dHRvbj5DbGljayBtZSE8L2J1dHRvbj4%3D)
265
+
266
+Conclusion
267
+----------
268
+
269
+JavaScript is a powerful tool you use every day, so I hope you gain a deeper understanding of its fundamental concepts as I have introduced them with sample code to help students comprehend the principles.
270
+
271
+Don’t stop there, though. If you want to be in the top **10% of JavaScript developers**, you should study these topics and their inner workings:
272
+
273
+> Object-oriented & functional Programming, prototype inheritance, modules, error handling, and types in javascript.
274
+
275
+
276
+**Cheers!**
277
+
278
+Follow me on [Medium](https://medium.com/@noor882) and [LinkedIn](https://www.linkedin.com/in/noorahmed11/) to remain up to date on new articles I’ll be writing!
279
+
280
+Bit: Feel the power of component-driven dev
281
+-------------------------------------------
282
+
283
+Say hey to [**Bit**](https://bit.cloud/). It’s the #1 tool for component-driven app development.
284
+
285
+With Bit, you can create any part of your app as a “component” that’s composable and reusable. You and your team can share a toolbox of components to build more apps faster and consistently together.
286
+
287
+* Create and compose “**app building blocks**”: UI elements, full features, pages, applications, serverless, or micro-services. With any JS stack.
288
+* Easily **share, and reuse** components as a team.
289
+* Quickly **update** **components** across projects.
290
+* Make hard things simple: [Monorepos](https://bit.cloud/blog/painless-monorepo-dependency-management-with-bit-l4f9fzyw), [design systems](https://blog.bitsrc.io/how-we-build-our-design-system-15713a1f1833) & [micro-frontends](https://blog.bitsrc.io/how-we-build-micro-front-ends-d3eeeac0acfc).
291
+
292
+[**Try Bit open-source and free→**](https://bit.cloud/)
293
+
294
+[](https://bit.cloud/)
295
+
296
+Learn more
297
+----------
... ...
\ No newline at end of file