A variable contains some value.
Declaring A Variable
We create a variable by using keywords var
, let
and const
followed
by a variableName.
Semicolon
In JavaScript, all code instructions should end with a semi-colon (;) — your code may work correctly for single lines, but probably won't when you are writing multiple lines of code together. Try to get into the habit of including it.
Initialize A Variable
After declaring a variable, let us initialize it with a value.
Naming Convention For A Variable
We can call a variable-name pretty much anything, but there are limitations. Generally, we should stick to just using Latin characters (0-9, a-z, A-Z) and the underscore character.
- We shouldn't use other characters because they may cause errors or be hard to understand for an international audience.
-
We shouldn't use underscores
_
at the start of variable name because this is used in certain JavaScript constructs to mean specific things, so may get confusing. - We shouldn't use numbers at the start of variables. This isn't allowed and causes an error.
- A safe convention to stick to and the most widely used is so-called "lower camel case" , where you stick together multiple words, using lower case for the whole first word and then capitalize subsequent words. We've used this for our variable names in almost all the tutorials.
- Make variable names intuitive, so they describe the data they contain. Don't just use single letters/numbers, or big long phrases.
-
Variables are case sensitive — so
firstname
is a different variable fromfirstName
. -
Last but not the least, we also need to avoid using JavaScript
reserved words
as variable name — by this, we mean the words that make up the actual syntax of JavaScript! So, you can't use words likevar
,function
,let
, andfor
as variable names. Browsers recognize them as different code items, and so you'll get errors.