0
0
Javascriptprogramming~5 mins

Function scope in Javascript

Choose your learning style9 modes available
Introduction

Function scope means variables created inside a function only exist inside that function. This helps keep things organized and avoids mistakes.

When you want to keep a variable private to a function so other parts of your code can't change it.
When you want to reuse the same variable name in different functions without conflicts.
When you want to make sure temporary data is removed after a function finishes running.
Syntax
Javascript
function functionName() {
  let variableName = value;
  // code using variableName
}
Variables declared with let or const inside a function are only available inside that function.
Variables declared without let, const, or var inside a function become global (avoid this).
Examples
This function prints 'Hello'. The variable message exists only inside greet.
Javascript
function greet() {
  let message = 'Hello';
  console.log(message);
}
greet();
Here, number is a constant inside the function and cannot be changed outside.
Javascript
function test() {
  const number = 5;
  console.log(number);
}
test();
var also creates a function-scoped variable, similar to let inside functions.
Javascript
function show() {
  var name = 'Alice';
  console.log(name);
}
show();
Sample Program

This program shows a variable counter inside the function count. It prints the value inside the function. Trying to access counter outside causes an error because it only exists inside the function.

Javascript
function count() {
  let counter = 0;
  counter = counter + 1;
  console.log('Counter inside function:', counter);
}

count();
// console.log(counter); // This would cause an error because counter is not visible here.
OutputSuccess
Important Notes

Variables inside functions cannot be used outside unless returned.

Using var, let, or const inside functions creates function scope.

Avoid creating global variables inside functions by forgetting let, const, or var.

Summary

Function scope keeps variables inside functions private.

Use let, const, or var to create function-scoped variables.

Variables inside functions cannot be accessed outside.