𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗕𝗮𝘀𝗶𝗰𝘀: 𝗩𝗮𝗿, 𝗟𝗲𝘁, 𝗧𝗵𝗿𝗲𝗮𝗱𝘀, 𝗮𝗻𝗱 𝗣𝗿𝗼𝗰𝗲𝘀𝘀𝗲𝘀
Understanding how JavaScript works helps you write better code. Here is a simple breakdown of variables and execution.
𝗭𝗲𝗿𝗼 𝘁𝗼 𝗩𝗮𝗿𝗶𝗮𝗯𝗹𝗲𝘀
JavaScript uses keywords to store data.
- var: This is the old way. It is function scoped. It allows you to redeclare variables, which causes bugs. It also uses hoisting, meaning you can access it before declaration as undefined.
- let: This is the modern way. It is block scoped. It does not allow redeclaration in the same scope. It stays in a temporal dead zone until you declare it.
- const: Use this by default for values that do not change.
Best practice: Use const first. Use let if the value must change. Avoid var.
𝗣𝗿𝗼𝗰𝗲𝘀𝘀 𝘃𝘀. 𝗧𝗵𝗿𝗲𝗮𝗱
Think of a house to understand these terms.
- Process: This is the house. It is a running program like Chrome or Spotify. It owns memory and resources.
- Thread: This is a person living in the house. It is the smallest unit of work. A process must have at least one thread.
Single-threading means one worker does everything. One task must finish before the next starts. This is simple but slower for big jobs.
Multi-threading means many workers act at once. One worker downloads a file while another plays music. This is faster but harder to manage.
𝗛𝗼𝘄 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗛𝗮𝗻𝗱𝗹𝗲𝘀 𝗧𝗮𝘀𝗸𝘀
JavaScript is a single-threaded language. It has one call stack and one main thread. It executes one statement at a time.
If you run a massive loop, your code stops until the loop finishes.
So how do timers or network requests work?
The browser provides extra help. When you use a timer, JavaScript hands that task to the browser. The browser handles the wait. Once the timer ends, the browser tells JavaScript to run the callback.
JavaScript is single-threaded but non-blocking. It uses the Event Loop and Web APIs to manage multiple tasks without stopping the main thread.
Summary of differences:
Scope
- var: Function scope
- let: Block scope
Execution
- Single Thread: One task at a time
- Multi Thread: Many tasks at once
Source: https://dev.to/dev_saravanan_journey/var-let-single-multi-thread-and-process-in-javascript-4j73