Scope determines where in your code a variable can be accessed. A variable declared inside a function generally can't be seen from outside it — that's not a limitation, it's what keeps different parts of a large program from accidentally interfering with each other.
A variable declared inside a function only exists inside that function.
function greet() {
let message = "Hello!";
console.log(message); // works fine
}
greet();
console.log(message); // ❌ ReferenceError: message is not defined<?php
function greet() {
$message = "Hello!";
echo $message; // works fine
}
greet();
echo $message; // ❌ Warning: Undefined variable $messagedef greet():
message = "Hello!"
print(message) # works fine
greet()
print(message) # ❌ NameError: name 'message' is not definedA variable declared outside any function is accessible everywhere in the file, including inside functions.
let siteName = "Learn Computer Academy"; // global
function printName() {
console.log(siteName); // can read the global variable
}
printName(); // "Learn Computer Academy"<?php
$siteName = "Learn Computer Academy"; // global
function printName() {
global $siteName; // PHP needs this explicitly — unlike JS, a
// function doesn't see outer variables on its own
echo $siteName;
}
printName(); // "Learn Computer Academy"site_name = "Learn Computer Academy" # global
def print_name():
print(site_name) # can read the global variable
print_name() # "Learn Computer Academy"Keeping variables local (rather than making everything global) prevents different parts of a program from stepping on each other's variables by accident — a common source of hard-to-find bugs in larger programs.