177. How Javascript works

변지영·2022년 3월 19일
0
post-thumbnail

How Does Javascript work?

Imagine getting this question during an interview.

Explain the difference between asynchronous and synchronous in Javascript.

Answer> Javascript as a single threaded language that can be non-blocking(자바스크립트는 비차단이 가능한 단일스레드 언어입니다.)

what is a program?

  • allocate memory
  • parse and execute scripts(구문 분석 및 실행) : read and run commands.
//these are global variables.
const a = 1;
const b = 10;
const c = 100;

With all memory we have limited amount, that we can actually have.

Memory Leaks

Memory leaks happen when you have unused memory.
Global variables are bad because there're unused memory.

call stack

console.log('1');
console.log('2');
console.log('3');

The call stack, if you remember, that's what it reads and executes our scripts.

  • 'Call Stack': it reads the first line, console.log.
    and it gets put in the call stack. JS engine says 'oop!, console.log has been added. Let's pop it onto this call stack.

let's imagine I have a function 'const one'

const one = () => {
	const two =() => {
		console.log('4')
	}
	two();
}

What happened here according to the Call Stack?

  • console.log('4')
    => print out number 4
    : executed and removed from the callstack.
  • two(); : and then remove the two
  • one(); : and then remove the one because it's just been called.
    (on top of the callstack)
    And the call stack is now empty.

Let's revisit the statement from the beginning.

Answer> Javascript as a single threaded language that can be non-blocking(자바스크립트는 비차단이 가능한 단일스레드 언어입니다.)

  • Single thread: it has only one call stack.
    => you can only do one thing at a time.
  • Call Stack is first in last out
    => Whatever's at the top of the call stack gets run first then below that, below that, below that.

Other language can have multiple call stacks which is called multithread. Multiple call stack might be beneficial, so that we don't keep waiting around for stuff.

Why was javascript designed to be single thread?

Single thread can be quite easy, since you don't have to deal with complicated scenarios that arise in multithreaded environment.

  • issues with Multithread envitonment: deadlocks.

Synchronous programing: execute line1, line2.. in order.

you know the site, stackoverflow.

Stack Over Flow means that a stack is overflowing.

Overflow happens when the call stack just gets bigger and bigger until it just doesn't have enough space anymore.

How can we makes over flow?

function foo() {
	foo()
}

It just keeps looping over and over, having recursion but there's no end in sight.
We keep adding foo to the call stack.
And we have a stack overflow.

  1. Javascript engine(v-8 engine) and Chrome has a memory heap and a call stack.
  2. Javascript is single thread, only one statement is executed at a time.

Problem: What if line two was a big task we needed to do?

console.log('1');
...
massive work : reallllly massive work.
...
console.log('3'); // take a long time to get logged.

The website would freeze until the task is done and the user just wait there.
Synchronous task: if we have one function that takes up a lot of time, it's going to hold up.

We need "nonblocking".
Javascript is a single threaded language that can be non-blocking.
Synchronous execution is great because it's predictable but it can get slow in tasks like image processing, making requests over the network like API calls.

We need something more that just synchronous tasks.

Then How we do asynchronous programming?

console.log('1');
setTimeout(() => {
	console.log('2');
}, 2000) // first parameter is the function that we want to run
// second parameter is how many milli seconds we want to wait.
console.log('3');

'console.log(2)' is done 2 seconds later.

//CALL STACK

//WEB API

//CALLBACK QUEUE

//EVENT LOOP

177. 15:29참고

What happend if the time is 2sec?

console.log('1');
setTimeout(() => {
	console.log('2');
}, 0) 
console.log('3');


execute consolelog3 first than 2

Issue of synchronous

Let's recap.
If you wanted to load your latest tweets onto a web page and you do this synchronously, then visitors to your website won't be able to do anything until those tweets are loaded.
This could cause a long delay they even get to see the content of his site.
They may not be able to click anywhere and the page will feel like it's frozen.

Do you remember eventListner?

element.addEventListener('click', () => {
	console.log('click')
})

Every time a click happens on the web page, on the DOM we run the callback function, which is console.log('click').

When is asynchronous happening?

when you try and talk between machines like speaking to a database making network requests, image processing, reading files...

summary

  • Javascript is a single threaded language that can be nonblocking.
  • It has one call stack and it does one thing at a time.
  • In order to not block the single thread, it can be asynchronous with call back functions and these callback functions gets run in the background through callback queue, the event loop, to bring it back to the call stack.

key questions

  • What is the difference between a synchronous or asynchronous program?
  • How does javascript work?

0개의 댓글