JavaScript Scope Flashcards

1
Q

What does Scope mean?

A

“Scope” is a concept that refers to where values and functions can be accessed.

Example:
function myFunction () {

var pizzaName = “Volvo”;
// Code here CAN use pizzaName

}

// Code here CAN’T use pizzaName

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How does a Global Scope work?

A

A value/function in the global scope can be used anywhere in the entire program.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How does a File or Module Scope work?

A

The value/function can only be accessed from within the file.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How does a Function Scope work?

A

It is only visible within the function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How does a Code Block Scope work?

A

It is only visible within a {…} codeblock.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are Block Scoped Variables?

A

“const” and “let” are “block scoped” variables, meaning they are only accessible in their block or nested blocks. In the given code block, trying to print the “statusMessage” using the “console.log()” method will result in a “ReferenceError”. It is accessible only INSIDE that “if” block.

Example:
const isLoggedIn = true;

if (isLoggedIn == true) {
const statusMessage = ‘User is logged in.’;
}

console.log(statusMessage);

// Uncaught ReferenceError: statusMessage is not defined

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are Global Variables?

A

JavaScript variables that are declared OUTSIDE OF blocks or functions can exist in the “global scope”, which means they are accessible throughout a program. Variables declared outside of smaller block or function scopes are accessible inside those smaller scopes.
Note: It is best practice to keep global variables to a minimum.

Example:
// Variable declared globally
const color = ‘blue’;

function printColor() {
console.log(color);
}

printColor(); // Prints: blue

How well did you know this?
1
Not at all
2
3
4
5
Perfectly