variables in javascript

Variables in JavaScript 

In JavaScript, a variable is a named  used to store data. It allow us to assign values to a name . Variables provide a way to manipulate and store data dynamically, making JavaScript a flexible and powerful programming language.

To declare a variable in JavaScript,  we use the var, let, or const keyword, followed by the variable name. Here's an example:

var age; // declaring a variable named 'age' using the 'var' keyword

let name; // declaring a variable named 'name' using the 'let' keyword

const PI = 3.14159; // declaring a constant variable named 'PI' using the 'const' keyword.

Var variable

The var keyword is used to declare the variable(fig i) . After declaring we can assign the value to the variable .for example : 

var a; // first  declare the variable

a=10; // then assign the value.

or , by a second method 

var a=10; // declaration and assigning the value can be done in same line .

we can further update the value of variable like ,

a=15; // value of a is updated in the same variable . 


Here is the another example : 

var age = 25; // declaring and assigning an initial value to 'age'

console.log(age); // Output: 25

age = 30; // updating the value of 'age'

console.log(age); // Output: 30


Let variable

Variables declared with let have block scope(fig ii) , meaning they are limited to the block of code in which they are defined. They can be accessed and updated within the same block or nested blocks, but not outside of that scope. 

example : 

let a=10; // we declare a variable by using let keyword.

let a = 10;

console.log(a); // Output: 10

{

  let a= 20; // This is a new variable 'a' within the block

  console.log(a); // Output: 20

}

console.log(a); // Output: 10 (accessing the outer 'a')

Const Variable

In JavaScript, the const keyword is used to declare a constant variable. A constant is a variable that cannot be reassigned ,once it has been assigned a value. It provides a way to declare values that are meant to remain unchanged throughout the execution of a program.

Here's an example of declaring and assigning a constant variable:

const pi = 3.14159;

Post a Comment

have you any doubt then ask.

Previous Post Next Post