Parameters & Arguments (Recap): Parameters are placeholders in the function definition. Arguments are the actual values supplied during the function call.
Return Values (Recap):
The return
statement specifies the value a function sends back to its caller. A function can only return one value, but this value can be an array or an object, allowing you to effectively return multiple pieces of data.
Scope: Scope determines the accessibility (visibility) of variables.
-
Global Scope: Variables declared outside of any function are in the global scope. They can be accessed from anywhere in your JavaScript code, including inside functions.
let globalVar = "I am global"; function showGlobal() { console.log(globalVar); } showGlobal(); // Output: I am global
-
Local Scope (Function Scope): Variables declared inside a function (using
let
,const
, orvar
) are in the local scope of that function. They can only be accessed from within that function.function myLocalScope() { let localVar = "I am local"; console.log(localVar); } myLocalScope(); // Output: I am local // console.log(localVar); // Error: localVar is not defined (outside its scope)
-
Block Scope (ES6+ with
let
andconst
): Variables declared withlet
andconst
inside a block (e.g., within{}
of anif
statement or afor
loop) are scoped to that block. They are not accessible outside that block.if (true) { let blockVar = "I am block-scoped"; console.log(blockVar); } // console.log(blockVar); // Error: blockVar is not defined
Understanding scope is crucial for avoiding naming conflicts and managing your program's data effectively. Generally, it's good practice to limit the scope of your variables as much as possible.