Thursday 1 August 2024

How to declare variable in Javascript?

In JavaScript, variables can be declared using the `var`, `let`, or `const` keywords. Each keyword has different characteristics and use cases:



  1. `var`: The `var` keyword declares a variable, optionally initializing it to a value. Variables declared with `var` have function scope if declared within a function, or global scope if declared outside any function.

 

   Javascript

   var name = "John";

   var age = 30;

   ```

 

  1. `let`: The `let` keyword declares a block-scoped variable, optionally initializing it to a value. Variables declared with `let` are limited to the block, statement, or expression where they are used.

 

   ```Javascript

   let name = "Jane";

   let age = 25;

   ```

 

  1. `const`: The `const` keyword declares a block-scoped variable, similar to `let`, but the variable must be initialized at the time of declaration, and its value cannot be reassigned.

 

   ```Javascript

   const name = "Alice";

   const age = 28;

   ```

 

Examples of Variable Declaration

 

- Using `var`:

 

   ```Javascript

   var greeting = "Hello, World!";

   var number = 42;

   var is JavaScript Fun = true;

   ```

 

- Using `let`:

 

   ```Javascript

   let greeting = "Hello, Universe!";

   let number = 7;

   let is Coding Fun = true;

   ```

 

- Using `const`:

 

   ```Javascript

   const pi = 3.14159;

   const maxScore = 100;

   const is Learning Fun = true;

   ```

 

Important Notes:

 

- Scope: `var` has function scope, whereas `let` and `const` have block scope.

- Reassignment: Variables declared with `var` and `let` can be reassigned. Variables declared with `const` cannot be reassigned.

- Hoisting: `var` variables are hoisted to the top of their scope and initialized with `undefined`. `let` and `const` are also hoisted but are not initialized, leading to a "temporal dead zone" until they are explicitly initialized.

TCCI Computer classes provide the best training in all computer courses online and offline through different learning methods/media located in Bopal Ahmedabad and ISCON Ambli Road in Ahmedabad.

For More Information:                   

Call us @ +91 98256 18292

Visit us @ http://tccicomputercoaching.com/

No comments:

Post a Comment