JavaScript Local Variables
Last Updated :
02 Aug, 2023
What are Local Variables in JavaScript?
JavaScript local variables are declared inside a block ({} curly braces) or a function. Local variables are accessible inside the block or the function only where they are declared.
Local variables with the same name can be used in different functions or blocks. Local variables are deleted after a function is completed.
Below are some examples to see the declaration and use of JavaScript local variables.
Example 1: In this example, we will see the declaration of local variables and accessing them.
Javascript
myfunction();
function myfunction() {
let course = "GeeksforGeeks" ;
console.log(course);
}
console.log(course);
|
Output
GeeksforGeeks
ReferenceError: course is not defined - in line 10
Explanation: A variable named course is declared inside a function and we printed its value in the console.
Example 2: In this example, we will declare local variables with similar names and try to access them.
Javascript
myfunc1();
myfunc2();
let course;
function myfunc1() {
let course = "GeeksforGeeks" ;
console.log(course);
}
function myfunc2() {
let course = "GfG" ;
console.log(course);
}
console.log(course);
|
Output
GeeksforGeeks
GfG
undefined
Explanation: A variable named course is declared and initialized inside two different functions. We get two different values in the console and at last undefined is printed because the variable is not initialized outside the functions.
Share your thoughts in the comments
Please Login to comment...