Core programming fundamentals · Lesson 12 of 60 · Code lesson, JavaScript or Python · Optional
Scope and lifetime
Scope is the part of a program where a name can be used.
A local variable lives inside one function and disappears when the function ends, while a global variable can be seen everywhere.
Code can look outward at the names around it (lexical scope), but not inward at a function's locals.
Worked example
In JavaScript, const and let belong to the nearest pair of curly braces, and a function can read names from the code around it.
const greeting = "Hello";
function shout() {
const ending = "!";
return greeting + ending;
}
console.log(shout());Output: Hello!
In Python, a name made inside def is local to that function, and a function can read names defined outside it.
greeting = "Hello"
def shout():
ending = "!"
return greeting + ending
print(shout())Output: Hello!
Your turn
This program crashes because message only exists inside makeMessage. Fix it so it prints Scope works!
Expected output: Scope works!
Loading your practice…
Preparing your workspace…