Hi there,
I am currently doing JS Data Structures and Algorithms → Global Scope and Functions
It says:
“In JavaScript, scope refers to the visibility of variables. Variables which are defined outside of a function block have Global scope. This means, they can be seen everywhere in your JavaScript code.”
" Variables which are declared without the let
or const
keywords are automatically created in the global
scope. This can create unintended consequences elsewhere in your code or when running a function again. You should always declare your variables with let
or const
."
Then the task:
Using let
or const
, declare a global variable named myGlobal
outside of any function. Initialize it with a value of 10
.
Inside function fun1
, assign 5
to oopsGlobal
without using the var
, let
or const
keywords.
The correct code is this:
// Declare the myGlobal variable below this line
const myGlobal = 10;
function fun1() {
// Assign 5 to oopsGlobal here
oopsGlobal = 5;
}
// console output
myGlobal: 10 oopsGlobal: 5
Can someone, please:
- first, explain this topic a little bit in a different way, somehow that has helped you to understand it better?;
- second, explain what’s the purpose of this particular task?
- third, are variables declared inside a function become Global or not? Or it depends on whether they are declared with or without
let
orconst
keywords?
Best regards!