Wednesday, 8 November 2017

How to Declare and Name the Variables in JS

In JavaScript,a variable contains a value, such as "hello" or 5. When you use the variable, you refer to the data it represents.You use variables to store, retrieve, and manipulate values that appear.

Description

Variables (JavaScript)
In JavaScript, a variable contains a value, such as "hello" or 5. When you use the variable, you refer to the data it represents. You use variables to store, retrieve, and manipulate values that appear in your code. Try to give your variables meaningful names to make it easy for other people to understand what your code does.
Declaring Variables
The first time a variable appears in your script is its declaration. The first mention of the variable sets it up in memory, so you can refer to it later in your script. You should declare variables before using them. You do this using the var keyword.
In JavaScript
// A single declaration.
var count;
// Multiple declarations with a single var keyword.
var count, amount, level;
// Variable declaration and initialization in one statement. var count = 0, amount = 100;
If you do not initialize your variable in the var statement, it automatically takes on the value undefined.
Naming the variables:
When choosing a variable name, you must first be sure that you do not use any of the JavaScript reserved names Found Here. Another good practice is choosing variable names that are descriptive of what the variable holds. If you have a variable that holds the size of a shoe, then name it "shoe_size" to make your JavaScript more readable.
Finally, JavaScript variable names may not start with a numeral (0-9). These variable names would be illegal: 7lucky, 99bottlesofbeer, and 3zacharm.
A good rule of thumb is to have your variable names start with a lowercase letter (a-z) and use underscores to separate a name with multiple words (i.e. my_var,strong_man, happy_coder, etc).

READ MORE

No comments:

Post a Comment