JavaScript Variable

·

2 min read

What is Variables in JavaScript?

Variables are used to store data. It is like a container, where we use to store things at home. To declare a variable in JavaScript, we use the var, let, or const keyword.

var x;

Here 'var' is the keyword to declare a variable and 'x' is the identifier or name of the variable.

We can also declare variable like:

let x; Or const x;

The var keyword is the oldest and most common way to declare variables.

The let keyword is a newer keyword that was introduced in ES6. (We will learn more about ES6 later in advance JavaScript).

The const keyword is used to declare constants, which are variables that cannot be changed.

var keyword:

Once you have declared a variable, you can assign a value to it using the equal sign (=).

For example: var x = 30;

the following code declares a variable called x and assigns it the value "30".

Variables can be used to store any type of data, including numbers, strings, objects, and arrays.

Example: var x = "Hello World"; //string.

A JavaScript variable name must begin with:

A letter (A-Z or a-z),

A dollar sign ($),

Or an underscore (_),

Subsequent characters may be letters, digits, underscores, or dollar signs. Numbers are not allowed as the first character in names.

JavaScript is case sensitive.

firstName and firstname are different.

Let keyword:

Let keyword in JavaScript is used to declare a block-scoped variable. This means that the variable is only visible within the block in which it is declared.

Example:

let x = 10;

if (x > 5) {

let y = 20; console.log(y); // 20

} console.log(y); // ReferenceError: y is not defined.

if you try to access the variable y outside of the if statement, you will get a ReferenceError. This is because the variable y is not defined outside of the if statement.

Const keyword:

The const keyword in JavaScript is used to declare a constant variable. This means that the variable cannot be reassigned to a new value.

Example:

const a =4;

console.log(a); // 4

a = 5 // Error: Cannot assign to constant variable

Did you find this article valuable?

Support Codec1 by becoming a sponsor. Any amount is appreciated!