Variables in JavaScript
In JavaScript, variables are used to store data values. The var, let, and const keywords are used to declare variables. Each type of variable declaration has its own scope and behavior.
var
The var keyword is used to declare a variable with either local or global scope. Variables declared with var are hoisted to the top of their scope, meaning they can be accessed before they are declared.
Here's an example of declaring a variable using var:
1var message = 'Hello, world!';
2console.log(message); // Output: Hello, world!let
The let keyword is used to declare a block-scoped variable. Variables declared with let are not hoisted, and they have block-level scope, meaning they are only accessible within the block they are declared in.
Here's an example of declaring a variable using let:
1let age = 25;
2if (age >= 18) {
3 let status = 'Adult';
4 console.log(status); // Output: Adult
5}
6console.log(age); // Output: 25const
The const keyword is used to declare a block-scoped variable that cannot be reassigned. Variables declared with const are not hoisted, and they have block-level scope.
Here's an example of declaring a constant using const:
1const PI = 3.14;
2console.log(PI); // Output: 3.14

