JavaScript var and Function Scope
Quick answer
var is an older declaration form. Inside an ordinary function its binding belongs to the function rather than an ordinary nested block. This difference matters when reading legacy programs.
How it works
A var binding in a function is available throughout that function and is initialized to undefined before the function body executes. An initializer is evaluated when its statement runs. Repeating a var declaration of the same name is allowed in many cases, but a conflicting lexical declaration can make the program invalid. At top level, script and module behavior differ; do not assume every var becomes a global object property.
function count() { { var items = 5; } return items;}console.log(count());Expected output in Node.js:
5The binding belongs to count.
function show() { console.log(total); var total = 14; console.log(total);}show();Expected output in Node.js:
undefined14The initializer has not run at the first read.
Common mistakes
Do not assume that braces isolate a var. Prefer let or const for new ordinary local code; when migrating old code, check whether it relies on function-wide visibility or redeclaration.
Practice
Rewrite the first example using let declared before the inner block, then assign inside the block and return it.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript var and Function Scope — Knowledge Check
Apply the taught concept and reason about the result.
What does function f() { { var n = 4; } return n; } console.log(f()); print?
What does function f() { console.log(n); var n = 9; } f(); display?
Which scope normally contains var declared in an ordinary function?
Which modern declaration would isolate a mutable binding in an ordinary block?
Why review legacy code before replacing every var with let?