Coding Schools


 
Python | C Sharp | Azure AI | HTML | JavaScript | CSS | SQL Server
JavaScript - Basic Structure
Closures in JavaScript
Using CSS in Javascript
OOPS in Javascript
Popup Window in Javascript
Printout a page in Javascript
Variable declaration in JavaScript
Difference of let, var and const
JavaScript - JSON Parse & Stringify

Variable declaration in JavaScript



In JavaScript, variable declaration is the process of creating a variable and optionally assigning it a value. There are three main ways to declare variables in JavaScript:

1. var

The var keyword was historically used to declare variables. Variables declared with var are function-scoped or globally scoped if declared outside a function. Here' an example:

javascript
var name = "Alice";
var age = 30;

2. let

The let keyword is used to declare block-scoped variables, meaning the variable is only accessible within the block it is declared in. It' a better practice to use let over var for variables that will change value or are declared in a block scope. Example:

javascript
let city = "Tokyo";
if (true) {
    let city = "Osaka";
    console.log(city); // "Osaka"
}
console.log(city); // "Tokyo"

3. const

The const keyword is used to declare block-scoped constants, meaning the value of the variable cannot be reassigned after its initial declaration. Example:

javascript
const PI = 3.14159;
const birthYear = 1995;

// The following will cause an error
// PI = 3.14;

Differences and Best Practices

  • Scope: var is function-scoped, while let and const are block-scoped.

  • Hoisting: Variables declared with var are hoisted to the top of their scope and initialized with undefined. Variables declared with let and const are also hoisted but are not initialized, which means accessing them before declaration will result in a ReferenceError.

  • Reassignment: let allows reassignment, while const does not.

Example Usage

Here' a practical example combining all three:

javascript
function example() {
    var x = 10; // function-scoped
    if (x > 5) {
        let y = 20; // block-scoped
        const z = 30; // block-scoped, constant
        console.log(x, y, z); // Output: 10 20 30
    }
    // console.log(y); // ReferenceError: y is not defined
    // console.log(z); // ReferenceError: z is not defined
}

example();

In summary:

  • Use const by default.

  • Use let if the variable needs to be reassigned.

  • Avoid using var to prevent unexpected behavior due to its function-scoping.

If you have any specific scenarios or further questions about variable declarations in JavaScript, let me know!




All rights reserved | Privacy Policy | Sitemap