javascript variable

What are JavaScript Variables?

JavaScript variables are containers used to store data values. These values can be of different data types including strings, numbers, booleans, objects, arrays, and more.

Declaring a variable in JavaScript is done using the var, let, or const keyword.

The var Keyword

The var keyword was the original way to declare variables in JavaScript. It has global scope by default and can be redeclared and reassigned within its scope.

var myVariable = "Hello World!";
document.write(myVariable); // Output: Hello World!

The let Keyword

The let keyword was introduced in ES6 as a replacement for the var keyword. It has block scope and can be reassigned but not redeclared within its scope.

let myVariable = "Hello World!";
document.write(myVariable); // Output: Hello World!
myVariable = "Goodbye World!";
document.write(myVariable); // Output: Goodbye World!

The const Keyword

The const keyword was also introduced in ES6 and is used to declare constants in JavaScript. It has block scope and cannot be reassigned or redeclared within its scope.

const myVariable = "Hello World!";
document.write(myVariable); // Output: Hello World!
// This will throw an error:
myVariable = "Goodbye World!";

It is best practice to use const for values that should never change, and let for values that may change in the future.

Overall, the choice of which keyword to use depends on the intended use of the variable and its scope.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe