// Using var (function-scoped)
var message = "Hello, world!";
var count = 42;
var isTrue = true;
// Using let (block-scoped)
let name = "John";
let age = 30;
let height = 1.75;
// Using const (block-scoped and read-only)
const PI = 3.14159;
const COLORS = ["red", "green", "blue"];
In these examples, var creates a variable that is function-scoped, meaning that it is accessible within the function in which it is declared. let and const create block-scoped variables, meaning that they are only accessible within the block in which they are declared (for example, within a loop or an if statement).
const variables are read-only, meaning that their value cannot be changed after they are declared. let and var variables, on the other hand, can be reassigned to a new value.
When declaring a variable, it’s good practice to give it a descriptive name that reflects its purpose. You can also initialize the variable with an initial value, although this is not always necessary.
Leave a Reply