JavaScript Variables

Like many other programming languages, JavaScript is flexible. Variables can be work as named containers. You can store data in these containers and refer to the data simply by naming the container.

Before using a variable in a JavaScript program, you must declare it. Variables are declared using the var keyword

<script type = "text/javascript">
   <!--
      var Sam;
      var Ram;
   //-->
</script>


Preserving value in variable  is called variable  initialization. You can perform initialization of the variable  during the creation of the variable  or at a later time when you need the change.

Note – Use the var keyword only for declarations or initializations, once for the lifetime of each variable name in the document. You can’t declare the same variable again.

JavaScript is untyped  language. This means that JS variables can store values of any datatype. Unlike many other languages, you don’t need to tell JavaScript when declaring a variable what type of value the variable will hold. The value type of a variable can change while the program is running, and JavaScript takes care of that automatically.

Scope of JavaScript Variables


The degree of flexibility is the area of your program that is defined. The JavaScript version has only two spaces.

Global variables – global variables have global scope, meaning they can be set anywhere in your JavaScript code.

Locale Variables – Locale variables will only be seen in jobs where they are defined. A service component is always available for the service. Within the body of a function, local variables take precedence over global variables with the same name. If you declare a local variable or scope variable with the same name as a global variable, you effectively hide the global variable. See the following example.
JavaScript variable Declaration Rules  
When naming your variables in JavaScript, keep these rules in mind.

  • You should not use any reserved JavaScript keywords as variable names. These issues are addressed in the next section. For example, a null or Boolean name is not changed.
  • JavaScript variable names must not start with numbers (0-9). They will start with letters or markers. For example, 123ule is an invalid variable name but _123ule is a valid name.
  • JavaScript variable are case sensitive . For example, Sam and sam are two different variables.

Javascript keywords
A list of all keywords set in JavaScript is provided in the following table. They cannot be used as JavaScript variables, functions, methods, loops, or any other object names.

abstractelseinstanceofswitch
booleanenumintsynchronized
breakexportinterfacethis
byteextendslongthrow
casefalsenativethrows
catchfinalnewtransient
charfinallynulltrue
classfloatpackagetry
constforprivatetypeof
continuefunctionprotectedvar
debuggergotopublicvoid
defaultifreturnvolatile
deleteimplementsshortwhile
doimportstaticwith
doubleinsuper