var keyword is used to declare a variable. It can optionally initialize the variable with a value.
var x; // declares a variable named x
var y = 10; // declares a variable named y and assigns it the value 10
One thing to note about
var is that it is function-scoped, not block-scoped. This means that if a variable is declared using
var inside a function, it can only be accessed within that function. But if it’s declared inside a block (like an if statement), it can be accessed outside that block.
let keyword, introduced in ES6, is similar to
var, but with some key differences. The main one is that
let is block-scoped, not function-scoped. This means that a variable declared with
let can only be accessed within the block where it was declared.
let x = 10; // declares a variable named x and assigns it the value 10
const keyword, also introduced in ES6, is used to declare variables whose values are never intended to change. This is known as a constant variable.
const PI = 3.14; // declares a constant variable named PI and assigns it the value 3.14
const is also block-scoped.
const depends on the needs of your program and how you intend to use the variable.