In this post we are going to focus on JavaScript Variables and their syntax. Variables are concept that exist in every programming language out there, and the basic concept is always the same. A variable is a container that has a name on it, and inside in that container we store data. So, variables are really important, they let us store some data and recall it later. Variables must be initialized before using. JavaScript has three ways to declare variables: var, let, const.

The syntax for a variables in JavaScript is very simple. It looks like this:

var myVariableName = myVariableValue  ( var (keyword) + myVariableName (this is up to us, whatever we want the variable to be called) + myVariableValue (the value that we assign) ).

// example :

var name = “Lena”;
var age = 2;
var isAdorable = true;

So now, whenever we ask for age, its going to give us 2. All JavaScript variables must be unique names, witch are called identifiers. In this case that is age.

The following rules apply to variable names:
-all variables names must be unique, and can not be duplicate.
-can not contain spaces
-can contain letters, digits, underscores, and dollar signs.
-are case sensitive (Q and q are different variables).
-reserved words (like JavaScript keywords) cannot be used as names.
-ending with a period should be avoided, since the period may be interpreted as a command terminator.

  • // Valid
    var name;
    var age3;
    var blackDog; // Suggested method named camel case
  • // Invalid
    var 1boy;
    var -boy;

In ES2015, two other ways to declare variables were introduced. They are let and const.

  • The let keyword allows a new variable to be assigned within the scope of a function or loop while not changing a variable that uses the same name that is outside of the scope of that function or loop. Let is usable in instances where the variable is going to be reassigned.
  • The const  keyword does not allow a variable name to be reused anywhere within your code. This means that if you assign a variable a name using the const keyword later on you cannot reset that variable to be equal to something else.

 

 

 

Spread the love

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *