codemarch
codemarch

@codemarch

14 Tweets 5 reads Aug 22, 2022
📌JavaScript Scope (Explained👇):::
Thread🧵
Scope refers to the availability of variables and functions in certain parts of the code.
In JavaScript, a variable has two types of scope:
→ Global Scope
→Local Scope
🔶 Global Scope
A variable declared at the top of a program or outside of a function is considered a global scope variable.
Example →
In the above program, variable 'language' is declared at the top of a program and is a global variable. It means the variable 'language' can be used anywhere in the program.
The value of a global variable can be changed inside a function.
For example,
In the above program, variable 'value' is a global variable. The value of 'value' variable is JavaScript. Then the variable 'value’ is accessed inside a function and the value changes to 100.
📝Note: It is a good practice to avoid using global variables because the value of a global variable can change in different areas in the program. It can introduce unknown results in the program.
In JavaScript, a variable can also be used without declaring it. If a variable is used without declaring it, that variable automatically becomes a global variable.
In the above program, variable 'language’ is a global variable.
If the variable was declared using let language = "hello JavaScript", then program would throw an error.
🔶 Local Scope
A variable can also have a local scope, i.e it can only be accessed within a function.
In the above program, variable a is a global variable and variable b is a local variable. The variable b can be accessed only inside the function greet. Hence, when we try to access variable b outside of the function, an error occurs.
let is Block Scoped
The let keyword is block-scoped (variable can be accessed only in the immediate block).
In the above program, variable
- a is a global variable. It can be accessed anywhere in the program.
- b is a local variable. It can be accessed only inside the function `greet`.
- c is a block-scoped variable. It can be accessed only inside the `if` statement block.
Hence, in the above program, the first two `console.log()` work without any issue.
However, we are trying to access the block-scoped variable c outside of the block in the third "console.log()". This will throw an error.
For more, you can go through this
If you enjoyed reading this thread, please do the following:
1. Like the thread❤️
2. Retweet the first tweet.🔃
3. Follow me and enable notifications: ✅
@CodeMarch
Thank you for reading all the way through.

Loading suggestions...