Thursday 28 February 2013

JavaScript : Variables, Constants, Data Type and Reserved Words


Variables

In our school life we learned about variables and equations in algebra. Let assume a=30, b=12 and c= a-b, then c=18, i.e. variables like a, b, c store numbers. In JavaScript and other programming language a variable contain values (piece of information) and stores in computer's memory which is changeable.

Naming variables

There are five rules for naming variables in JavaScript.
  • The first character must be a letter (a-z, A-Z) or an underscore (_).
  • The rest of the name can be made up of letters (a-z, A-Z), numbers (0-9) or underscore(_).
  • Variable name cannot contains space character.
  • In JavaScript variables are case sensitive, so emp_code is different from Emp_Code.
  • We should not use the "reserve words" like alert, var as variable name. See the list of Reserve Words.

Pictorial presentation of JavaScript variable naming

JavaScript variable naming

Invalid Variable Name

  • var // var is reserve word.
  • 77employee // Initial character is a number.
  • Variable%name // % character is not allowed.
  • Name&code // & is not allowed.

Valid Variable Name

  • employee_77
  • Variable_name
  • x
  • Name_code
  • name_code
  • _emp_name

Declaring Variables

We can declare a variable in the following way :
With the keyword var, followed by name of the variable. For example, to declare a new variable called emp_name, the statement is -
var emp_name
The above syntax can be used to declare both local and global variables.
Another way to declare a variable is simply assigning it a value. For example
  1. x=12.2  
  2. emp_code = 'E123'   
Therefore var x = 12.5 and x = 12.5 are equal.
// Declaring a variable
// Best Practices
var emp_code = 'E123';

// Poor Practices
emp_code = 'E123'
// Declaring multiple variables. Use one var statement and declare each variable on a new line.
// Best Practices
var emp_list = emplist(),
     x = 12,
     str1 = 'String1' ;

// Poor Practices
var emp_code = emplist();
var x = 12 ;
var str1 = 'String1';

Evaluating Variables

A variable or array element that has not been assigned a value, has the value undefined. The result of evaluating an unassigned variable depends on how it was declared:
If the unassigned variable was declared with var, the evaluation results in the undefined value or NaN in numeric contexts.
If the unassigned variable is declared without var statement, the evaluation results in a run time error.
See the following statements :
  1. var x;  
  2.  print("The value of x is : " + x); // prints "The value of x is : undefined"   
  3.  print("The value of y is : " + y); // throws reference error exception   
You can use undefined to determine whether a variable has a value.
In the following statements, the variable x is not assigned a value, and the if statement evaluates to true.
  1. var x;  
  2.   if(x === undefined)  
  3.   {   
  4.     do something ;  
  5.   }   
  6.   else  
  7.   {      
  8.     do something ;  
  9.   }   

Variables Usage

The variables can be declared and used in two ways locally and globally. When you declare a JavaScript variable within a function, it is called a local variable because the variable is available only within the function. You can use same variable name within different function. When you declare a variable outside a function it is called global variable.
You can optionally declare a global variable using var (for example var empCode). However, you must use var to declare a variable inside a function.

JavaScript : Constants

In JavaScript, constants are declared with const keyword and assigned at the time of the declaration. A constant can be global or local to a function where it is declared
Constants are read-only, therefore you can not modify them later on.
Naming a constant in JavaScript follow the same rule of naming a variable except that the const keyword is always required, even for global constants.
If the keyword is omitted, the identifier is assumed to represent a variable.

Rules for naming constants in JavaScript

  • The first character must be a letter (a-z, A-Z) or an underscore (_).
  • The rest of the name can be made up of letters (a-z, A-Z), numbers (0-9) or underscore(_).
  • Name of constant can not contains space character.
  • In JavaScript, constants are case sensitive, so emp_code is different from Emp_Code.
  • We should not use the the "reserve words" like alert, var as constants name. See the list of Reserve Words. 

Pictorial presentation of JavaScript constant naming

JavaScript constant naming

Example

  1. const country = 'India';  
  2. //You cannot declare a constant with the same name as a function  
  3. // or variable in the same scope. Following statements create error.  
  4. function abc()  
  5. {  
  6. const abc = 55;   
  7. }  
  8. function abc()  
  9. {   
  10. const x = 15;   
  11. var x;   
  12. }      

JavaScript : Data Type

A value is a piece of information that can be a Number, String, Boolean, Null etc. JavaScript recognizes the following types of values.
TypesDescriptionExample
StringA series of characters enclosed in quotation marks. A string must be delimited by quotation marks of the same type, either single quotation marks ( ') or double quotation marks (")."google.com", 'yahoo.com'
NumbersAny numeric value. The numbers can be either positive or negative.45, 45887, -45, 12.23, -145.55
Logical (Boolean)A logical true or false. Use to evaluate whether a condition is true or false.true, false
nullA special keyword denoting a null value (i.e. empty value or nothing). Since JavaScript is case-sensitive, null is not the same as Null, NULL, or any other variant. 
undefinedA top-level property whose value is undefined, undefined is also a primitive value. 

JavaScript : Data Type Conversion

JavaScript is a dynamically typed language. Therefore there is no need to specify the data type of a variable at the time of declaring it. Data types are converted automatically as needed during script execution.
For example, we define the age of a person in the 'age' variable as follows :
  1. var age = 21   
Let store a string value to the said variable.
  1. age = "What is your age?"  
As JavaScript is dynamically typed, the said assignment does not create any error.

JavaScript : Expressions

The following expressions contain string values, numeric values and + operator. JavaScript converts numeric values to strings. 
  1. x = "What is your age ?" + 21 // returns "What is your age ?21  "  
  2.   y = 21 + " is my age. " // returns "21 is my age."  
  3.                
The following expressions contain + and - operators.
  1. "21" - 7 // returns 14   
  2.  "21" + 7 // returns "217"  
  3.  "21" + "7" // returns "217"  
The following expressions contain * and / operators.
  1. "21" * 7 // returns 147  
  2.  "21" / 7 // returns 3  

JavaScript : Reserved Words

The words in the following table are reserved words and cannot be used as JavaScript variables, functions, methods, or object names. Some of these words are keywords, used in JavaScript ; others are reserved for future use.

List of reserved words

breakforthrow
casefunctiontry
catchiftypeof
continueinvar
defaultinstanceofvoid
deletenewwhile
doreturnwith
elseswitch 
finallythis 

The following words are reserved as future keywords

abstractexportlongsynchronized
booleanextendsnativethrows
bytefinalpackagetransient
charfloatprivatevolatile
classgotoprotected 
constimplementspublic 
debuggerimportshort 
doubleintstatic 
enuminterfacesuper 

1 comment: