DEV Community

Thui Sing
Thui Sing

Posted on

SCOPE,HOISTING,WINDOW

The scope is an accessibility part of you your code. Javascript has three types of scope. Today we will explain all three types of scope.

Block scope: Block scope is called when you declare a variable inside a curly bracket and it can be accessed only inside from curly bracket. If you call that variable outside of the curly bracket it will give you an error.

Image description
In this example, I declared a constant variable inside a curly bracket and I log that value inside that curly bracket it will show that value. On the bottom, you see that I log that variable outside the curly bracket and the result showed that the variable is undefined.

Function scope: when you declare a variable inside a function and that can be called inside from function and it can’t be called outside the function that is called function scope. Let’s see an example.

Image description
This function scope is like that curly bracket, when you call the variable outside the variable that will give us an error.

Global scope: Global scope is when you declared a variable top of your codes and it can be called from anywhere that’s called global. Let’s see an example and I will explain it.

Image description
I declared that greeting variable on top of code and it can be called from inside function and it can be called from anywhere from that’s why that is called global scope.

Hoisting: hosting is when you assigned a variable before the declaration. Hoisting allows functions to be safely used in code before they are declared. The variable is hoisted to. But const and let throw error when you use that code before declared but the var didn’t throw any error. Using var you can use that variable before declared.

Image description
In that example, var created hoisting and that output is undefined but var didn’t throw an error. if you use const or let it will throw an error.
Var is not recommended to use because it creates hoisted. Hoisted is good for function but it’s bad for variables and class.

Window: The window keyword gives us objects which represent a window of a browser. This window is a global object of javascript in the browser and exposes the browser‘s functionality.

Top comments (0)