Scope in JavaScript defines where variables and functions are accessible in your code, and it can behave differently depending on the environment (such as a browser or Node.js). There are four levels, from highest to lowest:
window object. For example, window.myGlobalVar = 'hello world' defines a global variable.global object: global.myGlobalVar = 'hello world'.<script type="module"> creates a module scope for that script.We'll cover modules in a later chapter.
var (we try to avoid this) are limited to the function scope. They are accessible only within that function and any nested functions.let and const keywords. A block is typically defined by curly braces {}, like in if statements, loops, and other blocks of code.let and const are confined to their block, making them more predictable and reducing the chances of accidental variable hoisting.While reviewing the Textio messaging system, you’ve come across a bug involving scope issues!
The function getMessageStatus returns the "status" of a message based on its length. It uses a nested helper function, isValidLength, to check if the message has more than 0 characters.
Fix getMessageStatus so that it uses the result of isValidLength to set the messageStatus.