𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗦𝗰𝗼𝗽𝗲: 𝗕𝗹𝗼𝗰𝗸, 𝗚𝗹𝗼𝗯𝗮𝗹, 𝗮𝗻𝗱 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻
Scope decides where you use a variable in your code.
Global Scope Variables live outside functions or blocks. You access them from anywhere in your script. Warning: Global variables lead to bugs because any part of your code can change them.
Function Scope Variables live inside a function. You only access them within that specific function.
Block Scope This applies to modern JavaScript using let or const. Variables live inside curly braces {}. A block includes:
- if statements
- for loops
- while loops
- standalone blocks {}
Summary of Scope:
- Global: Accessible everywhere.
- Function: Accessible only inside the function.
- Block: Accessible only inside the curly braces.
- var: Uses function scope. It ignores block scope.
- let and const: Use block scope. Use these for better code.
Understanding Processes and Threads
A process is a running program with its own memory. Think of WhatsApp as a process.
A thread is a small part of a process. Threads share the same memory.
- Threads are lightweight.
- They are fast to create.
- They allow you to do many things at once.
Example of WhatsApp: One process (WhatsApp) runs multiple threads:
- Receiving messages
- Sending photos
- Playing videos
- Showing notifications
Source: https://freeacademy.ai/lessons/global-vs-function-vs-block-scope Source: https://josephcardillo.medium.com/the-difference-between-function-and-block-scope-in-javascript-4296b2322abe