Here is the description of Variables and Data Types:
Variables are Containers for Storing Data.
• In JavaScript, variables are used to store and represent data values. Variables provide a way to label and reference data in your programs.
Variable Declaration:
Variables are declared using the var, let, or const keyword. In modern JavaScript, it’s recommended to use let and const for variable declarations.
let myVariable; // Declaration using let
var anotherVariable; // Declaration using var
const constantVariable = 42; // Declaration using const (immutable)
→ var:
- Variables declared with var have function scope or global scope.
- They can be re-declared within the same function or block.
- They can be updated.
function exampleVar() {
var x = 5;
var x = 10; // Re-declaration is allowed
if (true) {
var x = 20; // Updated
}
console.log(x); // Output: 20
}
→ let:
- Variables declared with let have block scope.
- They cannot be re-declared in the same scope.
- They can be updated.
function exampleLet() {
let y = 5;
// let y = 10; // Error: Cannot redeclare 'y' in the same scope
if (true) {
let y = 20; // Different block scope
console.log(y); // Output: 20
}
console.log(y); // Output: 5
}
const:
- Variables declared with const have block scope.
- They cannot be re-declared or updated.
function exampleConst() {
const z = 5;
// const z = 10; // Error: Cannot redeclare 'z' in the same scope
// z = 15; // Error: Cannot update 'z'
if (true) {
const z = 20; // Different block scope
console.log(z); // Output: 20
}
console.log(z); // Output: 5
}
Variable Initialization:
Variables can be assigned values during or after declaration.
let myVariable = "Hello, World!"; // Initialization with a string
var anotherVariable = 10; // Initialization with a number
Data Types:
JavaScript has several data types that can be categorized into two main groups:
- Primitive data types
- Object data types
7. BigInt:
Object Data Types:
- Object
- Array
- Function
- Date
Object:
Represents a collection of key-value pairs.
Examples:
let person = {
name: 'John',
age: 25,
city: 'New York'
};
Array:
Represents an ordered list of values.
Examples:
let fruits = ['apple', 'banana', 'orange'];
Function:
Represents a reusable block of code.
Examples:
function greet(name) {
return 'Hello, ' + name + '!';
}
Date:
Represents a date and time.
Examples:
let today = new Date();