Skip to main content

Command Palette

Search for a command to run...

JavaScript Variable

Published
2 min readView as Markdown
C

At Codec1, we believe that code is the language of the future. We're dedicated to bringing you the latest in programming and technology news, tips, and tutorials. Whether you're a beginner or an expert, we have something for everyone. Follow us for daily updates, exclusive content, and more. Let's code the future together.

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

More from this blog

C

Codec1

28 posts

At Codec1, we believe that code is the language of the future. Follow us for daily programming and tech updates, tips and tutorials. Let's code the future together.