0% found this document useful (0 votes)
53 views

Learn JavaScript - Scope Cheatsheet

This document discusses different scopes in JavaScript including global, file/module, function, code block, and block scoped variables. It explains that variables declared with const and let are only accessible within the block they are defined, while variables declared outside of blocks or functions exist in the global scope and can be accessed anywhere. It also notes that while global variables can be accessed from any scope, it is best practice to minimize their use.

Uploaded by

preeyal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views

Learn JavaScript - Scope Cheatsheet

This document discusses different scopes in JavaScript including global, file/module, function, code block, and block scoped variables. It explains that variables declared with const and let are only accessible within the block they are defined, while variables declared outside of blocks or functions exist in the global scope and can be accessed anywhere. It also notes that while global variables can be accessed from any scope, it is best practice to minimize their use.

Uploaded by

preeyal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Cheatsheets / Learn JavaScript

Scope
Scope
Scope is a concept that refers to where values and
functions can be accessed. function myFunction() {
Various scopes include:

var pizzaName = "Volvo";


● Global scope (a value/function in the global
scope can be used anywhere in the entire // Code here can use pizzaName
program)
}
● File or module scope (the value/function can only
be accessed from within the le)
// Code here can't use pizzaName
● Function scope (only visible within the function),

● Code block scope (only visible within a { ... }


codeblock)

Block Scoped Variables


const and let are block scoped variables, meaning
they are only accessible in their block or nested blocks. const isLoggedIn = true;
In the given code block, trying to print the
statusMessage using the console.log() method will
if (isLoggedIn == true) {
result in a ReferenceError . It is accessible only inside
const statusMessage = 'User is logged
that if block.
in.';
}

console.log(statusMessage);

// Uncaught ReferenceError:
statusMessage is not defined
Global Variables
JavaScript variables that are declared outside of blocks
or functions can exist in the global scope, which means // Variable declared globally
they are accessible throughout a program. Variables const color = 'blue';
declared outside of smaller block or function scopes are
accessible inside those smaller scopes.
function printColor() {
Note: It is best practice to keep global variables to a
minimum. console.log(color);
}

printColor(); // Prints: blue

You might also like