w3resource

JavaScript : Variables, Constants, Data Type and Reserved Words

JavaScript 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.

Standard: ECMA-262

Contents:

Valid identifier names

  • The first character must be a UnicodeLetter, an underscore (_), dollar sign ($), or \ UnicodeEscapeSequence
  • The rest of the name can be made up of starting character, UnicodeCombiningMark, UnicodeDigit, UnicodeConnectorPunctuation, <ZWNJ>, <ZWJ>
  • A variable name cannot contain 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 a variable name. See the list of Reserve Words.

UnicodeLetter: Uppercase letter (Lu)Lowercase letter (Ll)Titlecase letter (Lt)Modifier letter (Lm)Other letter (Lo), or Letter number (Nl).

UnicodeCombiningMark:  Non-spacing mark (Mn), Spacing combining mark (Mc).

UnicodeDigit: Decimal digit number (Nd), Connector punctuation (Pc) .

UnicodeEscapeSequence: Unicode escape sequences are also permitted in an IdentifierName, where they contribute a single character.

Invalid Variable Name

  • var // var is reserved 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

Test whether a variable is valid or not

A mostly reasonable approach to declare JavaScript Variables

Always declare variables in a consistent manner, and at the top of their scope. Keeping variable declarations to one per line is encouraged. Comma-first, a single var statement, multiple var statements and be consistent across the project.

// Bad Practice
var foo = 1,
    bar = 2;

var baz;
var pony;

var x
  , y;
//------------------------------
var foo = 1;

if (foo > 1) {
  var bar = 2;
}

// Good  Practice
var foo = 1;
var bar = 2;

var baz;
var pony;

var x;
var y;

//------------------------------
var foo = 1;
var bar;

if (foo > 1) {
  bar = 2;
}

Always use var to declare variables. Not doing so will result in global variables.

// bad
superPower = new SuperPower();

// good
var superPower = new SuperPower();

Declare unassigned variables last. This is helpful when later on you might need to assign a variable depending on one of the previously assigned variables.

// bad
var i, len, dragonball,
    items = getItems(),
    goSportsTeam = true;

// bad
var i;
var items = getItems();
var dragonball;
var goSportsTeam = true;
var len;

// good
var items = getItems();
var goSportsTeam = true;
var dragonball;
var length;
var i;

Assign variables at the top of their scope. This helps avoid issues with variable declaration and assignment hoisting related issues.

// bad
function() {
  test();
  console.log('doing stuff..');

  //..other stuff..

  var name = getName();

  if (name === 'test') {
    return false;
  }

  return name;
}

// good
function() {
  var name = getName();

  test();
  console.log('doing stuff..');

  //..other stuff..

  if (name === 'test') {
    return false;
  }

  return name;
}

// bad - unnecessary function call
function() {
  var name = getName();

  if (!arguments.length) {
    return false;
  }

  this.setFirstName(name);

  return true;
}

// good
function() {
  var name;

  if (!arguments.length) {
    return false;
  }

  name = getName();
  this.setFirstName(name);

  return true;
}

Hoisting

Variable declarations get hoisted to the top of their scope, but their assignment does not.

// we know this wouldn't work (assuming there
// is no notDefined global variable)
function example() {
  console.log(notDefined); // => throws a ReferenceError
}

// creating a variable declaration after you
// reference the variable will work due to
// variable hoisting. Note: the assignment
// value of `true` is not hoisted.
function example() {
  console.log(declaredButNotAssigned); // => undefined
  var declaredButNotAssigned = true;
}

// The interpreter is hoisting the variable
// declaration to the top of the scope,
// which means our example could be rewritten as:
function example() {
  var declaredButNotAssigned;
  console.log(declaredButNotAssigned); // => undefined
  declaredButNotAssigned = true;
}

Anonymous function expressions hoist their variable name, but not the function assignment.

function example() {
  console.log(anonymous); // => undefined

  anonymous(); // => TypeError anonymous is not a function

  var anonymous = function() {
    console.log('anonymous function expression');
  };
}

Named function expressions hoist the variable name, not the function name or the function body.

function example() {
  console.log(named); // => undefined

  named(); // => TypeError named is not a function

  superPower(); // => ReferenceError superPower is not defined

  var named = function superPower() {
    console.log('Flying');
  };
}

// the same is true when the function name
// is the same as the variable name.
function example() {
  console.log(named); // => undefined

  named(); // => TypeError named is not a function

  var named = function named() {
    console.log('named');
  }
}

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:

var x;
  print("The value of x is : " + x); // prints "The value of x is : undefined" 
  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.

var x;
if(x === undefined)
{ 
  do something ;
} 
else
{    
  do something ;
}

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 the same variable name within a 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.

How to check if a variable exist in javascript?

To check whether a variable is defined or not, you can use the typeof operator. The following alert will return "undefined" i.e. the variable "abc" is not defined.

You can use the following if statement to check whether a variable is defined or not :

if (typeof abc === 'undefined') {
    // variable abc is undefined
}

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.

Example:
const country = 'India';
//You cannot declare a constant with the same name as a function
// or variable in the same scope. Following statements create error.
function abc()
{
const abc = 55; 
}
function abc()
{ 
const x = 15; 
var x; 
}
 

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.

Types Description Example
String A 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'
Numbers Any 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
null A 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.  
undefined A 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 :

var age = 21 

Let store a string value to the said variable.

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.

x = "What is your age ?" + 21 // returns "What is your age ?21  "
  y = 21 + " is my age. " // returns "21 is my age."

The following expressions contain + and - operators.

 "21" - 7 // returns 14 
  "21" + 7 // returns "217"
  "21" + "7" // returns "217"

The following expressions contain * and / operators.

"21" * 7 // returns 147
  "21" / 7 // returns 3

JavaScript: Unicode escape sequences

Escape Sequence Code Unit Value Name Symbol
\b \u0008 backspace <BS>
\t \u0009 horizontal tab <HT>
\n \u000A line feed (new line) <LF>
\v \u000B vertical tab <VT>
\f \u000C form feed <FF>
\r \u000D carriage return <CR>
\" \u0022 double quote "
\' \u0027 single quote '
\\ \u005C backslash \

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:

break for throw
case function try
catch if typeof
continue in var
default instanceof void
delete new while
do return with
else switch  
finally this  

The following words are reserved as future keywords:

abstract export long synchronized
boolean extends native throws
byte final package transient
char float private volatile
class goto protected  
const implements public  
debugger import short  
double int static  
enum interface super  

Previous: JavaScript: Tools to create Web Application
Next: heading JavaScript Literals

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.