DEV Community

Raja B
Raja B

Posted on

JavaScript Scope: Block Scope, Global Scope & Function Scope

Scope = where a variable is accessible (where you can use it)

1.Global Scope

Definition:

Variables declared outside any function or block have global scope

Example:

glopal

Problem: Global variables can be changed from anywhere → bugs!

2.Function Scope (Local Scope)

Definition:

Variables declared inside a function have function scope. They are only accessible inside that function

Example:

local

3.Block Scope(ES6 - Modern JavaScript)

Definition:

Variables declared with let or const inside a block {} have block scope. They are only accessible inside that block

What is a Block?

Any code inside curly braces {}:

  • if statements

  • for loops

  • while loops

  • Standalone blocks {}

Example:

block

Key Takeaways:

  1. Global = accessible everywhere (declare outside functions)

  2. Function = only inside function (declare inside function() {})

  3. Block = only inside {} (declare with let/const inside blocks)

  4. var = function scope (NOT block scope)

5.let/const = block scope (modern, preferred)


Process: A running program that has its own memory and resources — like the WhatsApp application

Thread: A smaller part inside a process that shares the same memory — like WhatsApp downloading messages, playing videos, and sending photos at the same time

Thread = Lightweight process

  • Uses shared memory

  • Faster to create and manage than a process

  • Helps perform multiple tasks concurrently

Simple Example:

Process: WhatsApp

Threads inside WhatsApp:

  1. Message receiving thread

  2. Photo sending thread

  3. Video playing thread

  4. Notification thread

One process can contain multiple threads

Reference:

Top comments (0)