DEV Community

Khalil Dev
Khalil Dev

Posted on

JavaScript Variable

What is variable in programming language?
A variable is a named storage location that holds a value. Variables are used to store data values that can be used later in your code. The value of a variable can be changed, as well as its data type, throughout the execution of a program.

How to create variable in JavaScript?
To declare a variable in JavaScript, you use the var, let, or const keywords, followed by the variable name. Let's declare a few variable.

JavaScript Variable

Variable declared using var
The var keyword is used to declare a variable with function scope, which means that the variable is accessible within the entire function where it was declared.

Variable declaration using var

Variable declared using let
The let keyword is used to declare a variable with block scope, which means that the variable is accessible only within the block in which it was declared.

Variable declaration using let

Variable declared using const
The const keyword is used to declare a constant, which is a variable whose value cannot be changed.

Variable declaration using const

How to name a variable?
It's good practice to use descriptive names for your variables to make your code more readable and easier to maintain. Avoid using reserved words as variable names, and use camelCase or snake_case to separate words in your variable names

Summary
Variable is used to store data. In JavaScript, a variable is declared using var, let and const. It's best practice to give descriptive name to variable.

Thanks for reading.
Comment your thoughts and share if this can help others.

Top comments (4)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

Be careful how you describe const - the word 'changed' is ambiguous. An object/array stored in a const can have its contents changed (mutated). It's better to say that a const cannot be reassigned - to avoid confusion.

Collapse
 
khalildev profile image
Khalil Dev

Thanks for pointing out! Yes, a more meaningful term for 'change' is 'mutation', in this case.

Collapse
 
dimon1985 profile image
Dmitriy

In the last example you have an error, let is used instead of constant

Collapse
 
khalildev profile image
Khalil Dev

Oppss! the image is repeated.
Thanks Dmitriy for pointing that out.