Thursday, February 13, 2020

Variables In JavaScript

Variables In JavaScript


Variable


A variable is a container or portion of memory to store some data value temporarily to use somewhere in the program later(it may be changed during the program execution). A variable is identified by some identifier(unique) and some value is assigned by the assignment operator. An identifier is the valid sequence of characters for JavaScript. It is mandatory to declare a variable before using it.


Creating the variable in JavaScript


javascript variable


var x=10;
var b="Welcome to JavaScript";
var f=13.26;


What are the rules for Naming Variables in JavaScript?


  • The variable name can not contain spaces.
  • The first character of the variable name must be a letter or an underscore (_) or dollar sign ($).
  • The remaining name of the variable name may contain any letter, number, dollar or the underscore. Other characters including spaces, symbols, and punctuation marks are not allowed in the variable name.
  • JavaScript is a case sensitive language it means variable names are also case sensitive OR variable name Lastname and LastName are different.
  • There's no limit to the length of the variable name.
  • Any of the JavaScript's reserved keywords can not be used as a variable name.


Declaring the variables in JavaScript


We can declare a variable in JavaScript

var k;
var name;

but, if we use them then they still have a value undefined. Variables in JavaScript can obtain several types like Number, String, or boolean. Once we provide them some value then we will obtain that value

k=12;
name="Harry";

We can also re-declare the variables, like

var name=50;
document.write(name);
var name="Harry";

Example



<html>
  <head>
    <title>Variables</title>
  </head>
  <body bgcolor='yellow'>
    <script>
      var k;
      var a=10;
      var b=30;
      var fname="Harry";
      var lname="Potter";
      document.write(fname+' '+lname);
      document.write('<br>');
      document.write('Sum = '+(a+b));
      document.write('<br>');
      document.write('k is '+k);
      var b="James Bond";
      document.write('<br>')
      document.write('re-declared var b is now '+b);
/*
Output:
Harry Potter
Sum = 40
k is undefined
re-declared var b is now James Bond
*/

    </script>

  </body>
</html>