const globalVar = 100_000
function func() { // (A)
const alpha = 10;
if (true) { // (B)
const beta = 20;
} else {
console.log({beta, alpha})
const charlie = 30
}
}
There are basically 4 types of scopes possible in Javascript:
Function Scope:
const globalVar = 100_000
function func() { // (A)
const alpha = 10;
if (true) { // (B)
const beta = 20;
} else {
console.log({beta, alpha})
const charlie = 30
}
}
console.log(alpha) // undefined
var common = 300;
function newFunc(){
var common = 200;
console.log({common})
}
console.log({common})
newFunc()
console.log({common})
Block Scope ({}
):
{}
) "curly brackets" also create a scope.function func() { // (A)
const alpha = 10;
if (true) { // (B)
const beta = 20;
} else {
console.log({beta, alpha})
const charlie = 30
}
}
for (const num of [1,2,3,4]) {
// a block
}
if (condition) {
// a block
} else {
// another block
}
switch(name) {
// a block
case "yash":
console.log(name)
break;
}
Creating private variables:
function func(){
var isolatedVar = 100
}
console.log(isolatedVar) // undefined
isolatedVar = 300; // 'isolatedVar' is not defined
{
const blockConstant = 200;
let blockLet = 400;
}
console.log(blockConstant) // undefined
blockLet = 600; // 'blockLet' is not defined
Global Scope (ES6):
index.html
index.js
index.css
global - (window)
variables declared using "var" gets added to the global object:
<script>
tags// fileA.js
var someVar = 100
const nextVar = 500
// fileB.js
console.log(someVar) // 100
console.log(nextVar) // undefined
window.someVar // 100
window.nextVar // undefined
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="fileA.js"></script>
<script src="fileB.js"></script>
</head>
<body>
<div>Hello World</div>
</body>
</html>
Module Scope (ES6):
type="module"
<script type="module">
tag,<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="module" src="fileA.js"></script>
</head>
<body>
<div>Hello World</div>
<script type="module" src="fileB.js"></script>
</body>
</html>
type="module"
to each of the script tags,<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="fileA.js" type="module"></script>
<script src="fileB.js" type="module"></script>
</head>
<body>
<div>Hello World</div>
</body>
</html>
// fileA.js
var newVariable = 100
const nextVar = 500
// fileB.js
console.log(newVariable) // undefined
console.log(nextVar) // undefined
window.newVariable // undefined
window.nextVar // undefined
Global Objects:
window
- browsersglobal
- Node.JsglobalThis
- used to refer to global object of the environmentindex.html
index.js
index.css
global - (window)