📌JavaScript Scope (Explained👇):::
Thread🧵
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
In JavaScript, a variable has two types of scope:
→ Global Scope
→Local Scope
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 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.
If the variable was declared using let language = "hello JavaScript", then program would throw an error.
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
let is Block Scoped
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.
- 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
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.
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...