JavaScript Variables

JavaScript Variables:

Variables are name containers. JavaScript is not a strongly typed language. The programmer needs to care only what variable is storing.

In JavaScript the variables can store anything, even functions. Before using a variable in a JavaScript program, it must be declared.

Variable means anything that can vary. JavaScript includes variables which hold the data value and it can be changed anytime.

Syntax:


	var variable_name;

Here, var is the keyword and is optional, Any variable in JavaScript is declared without speciffying its data type. The variable takes the type of the value it holds.

Examples:

Naming variables:

  • Keywords in JavaScript cannot be used as a valid variable name.
  • JavaScript variable names should not start with a numeral(0-9). They must begin with a letter or the underscore character.
  • JavaScript variable names are case sensitive.

Scope of a variable:

The lifetime of the JavaScript variables starts when they are declared, and ends when the page is closed. The scope of a variable is the region of he program in which it is defined.

JavaScript variables will have only two scopes:

  • Global Variables: A global variable has global scope which means it can be accessed everywhere in the JavaScript code of the web page. If a function defines a new variable without using the var keyword, that variable will be a global variable.
  • Local Variable: A local variable will be visible only within a functuion where it is defined. Function parameters are always local to that function.

Example:


Result :

	This is a
	This is a string
	67