Variables are used to store data temporarily in a computer's memory.
- So, computer
store datasomewhere and give that a memory
- And with that
namewe can read the data at the given location.
- See the example below↓
myNumberis the name of variable stored in a computer memory having value
23at a computer assigned address.
Variable Declaration in Code.
ES6 we user
var keyword to declare a variable. But, from ES6 best pratice is to use
let keyword to declare a variable.
- Declare a variable begin with
- then variable
nameor an identifier.
- terminate this declaration with
- Example see below↓
Now, let's log the value of variable name in the console .
We can see (in image below↓) the value of variable name in the console at line no. 6 comes
We can (optionally) initialize the variable with string (which is a sequence of characters).
We can use single quote
'Akhil' OR double quote
let name = 'Akhil';
Rules for Naming these Variables.
functionthese are reserved keyword.
- Variables name should be meaningful. The should not be
x. The variable name should give us a clue what is the purpose of the variables. It's best practice to always use meaningful and descriptive names.
- The variable name can-not start with a number. Example of
incorrectvariable name declaration
- Variable name can-not contain a
hyphen. Example of
- Correct way to declare variable with multiple words are
let firstName = 'Akhil';
- Variable names are case-sensitive, see ↓ example: these two variables are different.
- There are two ways to declare multiple variables.
We can declare multiple variables in one line and separate them using comma ,
let firstName, lastName; ← Valid (with default value undefined)
let firstName = 'Akhil', lastName;← Valid (one initialized and one undefined, we can initialize both this way)
But, it's best practice to declare evey variable in a single line.
let firstName; ← Best practice (declare one variable in a single line)
let firstName = 'Akhil'← Best practice (declare one variable in a single line)
In this article we have covered:
How to declare variables and rules for naming these variables.
Next will be soon!