𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀, 𝗧𝗵𝗿𝗲𝗮𝗱𝘀, 𝗮𝗻𝗱 𝗔𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 𝗘𝘅𝗲𝗰𝘂𝘁𝗶𝗼𝗻
You need to understand how JavaScript works under the hood.
Here is a breakdown of functions, processes, threads, and execution styles.
𝗞𝗶𝗻𝗱𝘀 𝗼𝗳 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀
- Named Function: Uses a specific name. This makes debugging easy.
- Anonymous Function: Has no name. You often use these as callbacks.
- Function Expression: You assign a function to a variable.
- Arrow Function: A shorter syntax using the => symbol.
- IIFE: An Immediately Invoked Function Expression. It runs as soon as you define it.
𝗣𝗿𝗼𝗰𝗲𝘀𝘀 𝘃𝘀. 𝗧𝗵𝗿𝗲𝗮𝗱
A Process is a program running on your computer.
- Each process has its own memory.
- If one process crashes, others keep running.
- Example: Chrome and Spotify are separate processes.
A Thread is a small unit inside a process.
- Threads share the same memory.
- They allow a single program to do many things at once.
- Example: Inside Chrome, one thread renders a page while another handles your mouse clicks.
𝗦𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 𝘃𝘀. 𝗔𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀
JavaScript is single-threaded. It handles one task at a time using a call stack.
Synchronous Execution:
- Tasks run one after another.
- Each task waits for the previous one to finish.
- Slow tasks block your code from running.
Asynchronous Execution:
- Tasks run in the background.
- Code does not stop while waiting for a task to finish.
- This uses Web APIs, a Callback Queue, and an Event Loop.
How Asynchronous works:
- JavaScript sends a task (like a timer) to a Web API.
- The main code keeps running.
- Once the task finishes, it moves to the Callback Queue.
- The Event Loop moves it to the Call Stack when the stack is empty.
This keeps your web apps fast and responsive.