Javascript Variable

In JavaScript, variables are used to store and manage data. Here's a brief overview of how to declare, assign values and use variables in JavaScript:

Variable Declaration:

You can declare a variable using the var, let or const keyword.
  • var: Function-scoped variable (avoid using var in modern JavaScript).
  • let: Block-scoped variable allows reassignment.
  • const: Block-scoped variable constant (cannot be reassigned).
let myVariable; // Declaration without assignment
const PI = 3.14; // Declaration and assignment for a constant

Variable Assignment:

You can assign values to variables using assignment operator =.

let myNumber = 42;
let myString = "Hello, JavaScript!";

Variable Types:

JavaScript is dynamically typed meaning you don't need to explicitly declare the variable type. It can hold various types of values.

let numberVar = 42; // Number
let stringVar = "Hello"; // String
let booleanVar = true; // Boolean
let arrayVar = [1, 2, 3]; // Array
let objectVar = { key: "value" }; // Object

Variable Scope:

Variables can have different scopes:
  • Global Scope: Accessible throughout the entire program.
  • Local/Function Scope: Accessible only within the function where it is declared.
  • Block Scope (let/const): Accessible within the block where it is declared (e.g. if statements or loops).
function exampleFunction() {
let localVar = "I am a local variable";
console.log(localVar);
}
console.log(localVar); // Error: localVar is not defined


Variable Hoisting:

The JavaScript hoists variable declarations meaning you can use a variable before it is declared.

console.log(myVar); // undefined
var myVar = "I am hoisted!";
console.log(myVar); // I am hoisted!

Dynamic Typing:

Variables can change types during the runtime.

let dynamicVar = 42;
console.log(dynamicVar); // 42
dynamicVar = "Now I'm a string!";
console.log(dynamicVar); // Now I'm a string!