Key Concepts:
- Function scope: 'var' variables are accessible only within the function where they are declared.
- Re-declaration: 'var' variables can be re-declared within the same scope.
- Re-assignment: 'var' variables can be re-assigned with new values within the same scope.
Practical Steps:
- Declaration: Use the 'var' keyword followed by the variable name.
- Initialization: Assign a value to the variable upon declaration (optional).
- Scope: The variable is accessible within the function where it is declared.
- Re-declaration: Re-declare the variable using 'var' and a new name within the same scope.
- Re-assignment: Assign new values to the variable within the same scope.
Example:
// Oldest way to declare variables in JavaScript
var age = 25; // Function-scoped variable
function getAge() {
// Re-declare variable with new name
var age = 30;
// Re-assign variable with new value
age = 35;
// Access variable within function scope
console.log(age); // Output: 35
}
getAge();
// Access variable outside function scope
console.log(age); // Output: 25
Accessibility and Ease of Use:
- Use 'var' sparingly, as it can lead to variable name conflicts.
- Prefer 'let' and 'const' for block-scoped and constant variables, respectively.
- Ensure proper variable naming and documentation for clarity.
- Use code linters to enforce best practices and identify potential issues with 'var' usage.