programminghead Logo

JavaScript :

JavaScript often known as JS, is a high-level, interpreted programming language. Its very popular for its dynamic, weakly typed, prototype-based and multi-paradigm programming.
In HTML its very impotent Because using JavaScript we can Program HTML Elements and change any HTML Element without Refreshing the Current page.

JavaScript in HTML :

As we know that HTML is used to Create layout for our website/Web-page and CSS used to Design/Style that Web-page's Elements. Because HTML is a Markup Language we have to use Programming Languages like JavaScript to do Programming inside HTML Webpage.
We can Create JavaScript Program inside HTML Document and we also include External JavaScript file inside HTML Document.

JavaScript inside HTML Document :

There is ways to Use or Include JavaScript Program inside HTML Document.

1. Internal JavaScript.
2. External JavaScript.

1. Internal JavaScript :

Using JavaScript Internally is very easy and commonly used way to do programming inside HTML Document. For internal JavaScript we have script <script< Tag for that.

Script Tag <script> :

Script Tag used to define JavaScript inside HTML document. we can use this <script> Tag inside <head> Tag and also <body> body tag.
if you want to run your JavaScript before your HTML Element's data then you have to define javaScript inside <head> tag. Because when our browser starts loading our HTML Document's data then the data inside the <head> tag will going to load first.
If you want to load your JavaScript after the HTML Documents the you can define JavaScript inside <body> Tag after the HTML Elements.

JavaScript Syntax inside HTML


<html>
 <head>
  <title>JavScript inside HTML</title>
 </head>
 <body>

   <script type="text/javascript">
     alert("hello worls");
   </script>

 </body>
</html>

Results


Script Tag <script> :

Script tag is used to define JavaScript inside HTML Document.

type attribute type="" :

Type attribute defines the language of the script or format of the data inside Script tag.

alert() method:

The alert() method displays an alert box with a specified message that we wrote inside the alerts double quotes.

2. External JavaScript :

Using External JavaScript file in HTML Document is a great way to manage your Codes. For including External JavaScript file first we have to write a JavScript code and Save that code file with the dot JS extension (javaFile.js).
And in HTML document we have to use Script <script> and inside the src="" attribute of script tag we have to give our source file/javaScript file's path.

External JavaScript Syntax


<html>
 <head>
  <title>JavScript inside HTML</title>

   <script type="text/javascript" src="myjavascript.js">
   </script>

 </head>
 <body>

 </body>
</html>

myjavascript.js file


 alert("hello worls");

Script Tag <script> :

Script tag is used to define JavaScript inside HTML Document.

type attribute type="" :

Type attribute defines the language of the script or format of the data inside Script tag.

src attribute type="" :

src attribute defines the Path for External JavaScript file.

alert() method:

The alert() method displays an alert box with a specified message that we wrote inside the alerts double quotes.

note:

Here we have 2 file. one file with .html extension and other one with .js Extension. if both the .html and .js file is on the same same folder, we only have to give file name with file extension (myjavascript.js) but if our javaScript file/.js file is in another folder/directory then we have to give full path of that .js file with file name and with file extension (C:/Desktop/HTML/myjavascript.js)

writing your name using JavaScript :

There are several ways to print/output some texts using JavaScript.
so in this example we are going to use these 3 JavaScript Methods to Print some text in output.
1. document.write();
2. alert();
3. console.log();

document.write() JS method:

This method of JavaScript print the Given text on the output scree. Here document targets the body part of the Browser and write defines/takes the value to display on the Output Screen.

document.write method's Syntax



 <html>
  <body>

   <script type="text/javascript">
     document.write("text");
   </script>

  <body>      
 <html>

alert() JS method:

This method displays the given text inside a alert Box. As a result you will see a small alert box over our browser displaying your given text and a ok button.

JS alert method's Syntax


 <html>
  <body>

   <script type="text/javascript">
     alert("text");
   </script>

  </body>
 </html>

JS console.log() Method :

This method of displaying text is little tricky. because you can't see your text in your browser body or in the alert box. to see your text you have to visit your browser's console menu. You can visit your Browser Console menu by pressing ctrl+shift+i keys combinations in Windows OS systems or you can right click inside your browser body and select inspect/inspect element option.

JS console.log() method's Syntax


 <html>
  <body>

   <script type="text/javascript">
     console.log("text");
   </script>

  </body>
 </html>

Printing Your name Using JavaScript

JS console.log() method's Syntax


<html>
 <head>
  <title>My Name using JS</title>
 </head>
 <body>
  <script type="text/javascript">
   document.write("programminghead.com");
   alert("programminghead.com");
   console.log("programminghead.com");
  </script>
 </body>
</html>t;
 </html>

Results

Selecting HTML Elements:

we have 2 Different ways for Selecting HTML Elements so we can add/change there Contents.
1. Changing HTML Content by id
2. Changing HTML Content by Tag Name

Changing HTML Content by id :

We can use HTML Element's id to make change in the HTML Element's Content.
to select HTML Element's ID we have to use JavaScript's document.getElementById('') method.

document.getElementById('') Method :

Using JavaScript's document.getElementById('') Method we can select/target HTML's Elements in JavaScript so we can make change in the Element's Content.
here document targets the whole HTML Document and getElementById select the HTML Element of given ID Between the single/double quotes.
But this will only select HTML Element's id, to make change in the Content we have to use .innerHTML property for that.

.innerHTML property

after selecting HTML Element this JavaScript's .innerHTML property defines the HTML Content for Selected HTML Content.

Changing Content by id Example


<html>
 <head>
  <title>Changing Content by id </title>
 </head>
 <body>
   <p id="myparagraph"> </p>
   <script type="text/javascript">
     document.getElementById('myparagraph').innerHTML="text for HTML Element by JS";
   </script>

 </body>
</html>

Results


text for HTML Element by JS



Script Tag <script> :

Script tag is used to define JavaScript inside HTML Document.

type attribute type="" :

Type attribute defines the language of the script or format of the data inside Script tag.

document.getElementById('') method:

Using JavaScript's document.getElementById('') Method we can select/target HTML's Elements in JavaScript so we can make change in the Element's Content.

.innerHTML property :

after selecting HTML Element this JavaScript's .innerHTML property defines the HTML Content for Selected HTML Content.

Changing HTML Content by Tag Name :

We can use HTML Element's TagName to make change in the HTML Element's Content.
to select HTML Element's Tag we have to use JavaScript's document.getElementsByTagName('') method.

document.getElementsByTagName('') Method :

Using JavaScript's document.getElementsByTagName('') Method we can select/target HTML's Elements in JavaScript so we can make change in the Element's Content.
here document targets the whole HTML Document and getElementsByTagName('') select the HTML Element of given Tag Name Between the single/double quotes.
But this will select all HTML Elements if you have more then 1 elements created using same tag, But if you want to make change in only one HTML Element's content then you can create a Element with unique tag or you can give that Element unique id and change content using previous document.getElementById('') method.
if your HTML Document have multiple tag para tag and you still want to target that para tag, than you have to give index number document.getElementsByTagName('p')[0] after writing your tag name, so JavaScript can understand which tag to target. after selecting your HTML Element we have to use .innerHTML property to make change in the Element's Content.

.innerHTML property

work exactly the same for this method, after selecting HTML Element by TagName this JavaScript's .innerHTML property defines the HTML Content for Selected HTML Content.

Changing Content by TagName Example


<html>
 <head>
  <title>Changing Content by id </title>
 </head>
 <body>
    <p> first para </p><br/>
    <p> second para </p><br/>
    <p> third para </p>
   <script type="text/javascript">
     document.getElementsByTagName('p')[0].innerHTML="text of selected paragraph tag";
   </script>

 </body>
</html>

myjavascript.js file


text of selected paragraph tag


second para


third para


Script Tag <script> :

Script tag is used to define JavaScript inside HTML Document.

type attribute type="" :

Type attribute defines the language of the script or format of the data inside Script tag.

document.getElementById('') method:

Using JavaScript's document.getElementById('') Method we can select/target HTML's Elements in JavaScript so we can make change in the Element's Content.

.innerHTML property :

after selecting HTML Element this JavaScript's .innerHTML property defines the HTML Content for Selected HTML Content.

[0] index number after tagName :

in case of Multiple tags index [0] number helps JavaScript to target correct tag.
index number starts from 0 so
[0] is the first tag
[1] is the second tag
[2] is the third tag

Getting all HTML Document's Tag and id Name:

using "*" star parameter we can get all HTML Tags present on the current Document.
for that we have to just write "*" star parameter in the place of id and tag name and print that value in the output screen using document.write() method.

JavaScript Tutorial 3 : JavaScript Variables

JavaScript Variables :

Variables in JavaScript like a Container for Data values, which can store data for current program.
JavaScript Variable can store numbers, strings and Boolean values.

Declaring Variables in JavaScript :

In JavaScript Variable declaring is Easy. You just have to write var (stands for Variable) and then assign any name to your Variable.
You can write your variable according to your imagination And you also can Declare multiple variable in one line like (var myvar1, myvar2, myvar3;) but there is sum rules you have to keep in mind while Declaring or assigning Name for Variables in JS.

Rules for assigning Variable Names :

Rule 1: Variable are Case Sensitive
variables are Case sensitive, so Myvariable is compliantly different from myvariable.
Rule 2: Variables Name can not start with a number
while Declaring Variable you have to sure about there is not any number at the bigging of variable name. you can use number after or at the middle the Variable name like ( var data1;) but not at the beginning (var 1data;). Rule 3: The ampersand (&) character is not a valid for variable names
Yes The ampersand (&) character is not a valid character for variable names, you can't use THe The ampersand (&) character in Variable name.

Valid and Invalid Variable names :

Valid Variable names Example :


var _myvariable;
var myvar1;
var var_one;

Invalid Variable Names Example :


var 1myvar;
var var&data;

Variables syntax In JS

Variable syntax is very simple but in this Example I'm going to write 2 syntax one for Internal JavaScript in HTML Document and other one for External JavaScript file (.js file).
This is not that impotent to declare these Variable syntax separately but it will help beginners to understand better.

JS Variable Syntax for Internal JS in HTML


<html>
 <head>
  <title>Variables in JS</title>
 </head>
 <body>

   <script type="text/javascript">
     var myName;
     var myHobby1,myHobby2,myHobby3;
   </script>

 </body>
</html>

JS Variable Syntax for Internal .js file


   var myName;
   var myHobby1,myHobby2,myHobby3;

Assigning Value to JS Variables :

After Declaring a Variable in JS we Have to Assign Data to our Variable Otherwise Variable remains Undefined/Empty. We can assign values Like (string/numbers/boolean) To our Variable after the equal sign. var a=10;
so we can access those Values by calling that variable with the Value we need.
Like a have a 3 Variable called my Address (address1,address2,address3) with my address details.
and i want to output my 3rd address. so in JS except writing that long 3rd address again i can just call the Variable with my 3rd address in my program to save time and my strength. :p

Assigning String Values to JS Variables


<html>
 <head>
  <title>String Variables in JS</title>
 </head>
 <body>

   <script type="text/javascript">

     var myAddress1,myAddress2,myAddress3;
     myAddress1 = "house number 0, Fav Street, HUMANcountry";
     myAddress2 = "house number 1, Clean Street, Mycountry";
     myAddress3 = "house number 3, My Street, People'scountry";

     document.write("my 3rd Address = "+myAddress3);
   </script>

 </body>
</html>	

You also can assign values in the same line or while declaring variables like
var address="hose number, street name, country";
after the Variable names but for better understanding i had declared all variable once and the values after the Declaration.

+ Concatenation sign in Code :

This + sign is Called concatenation in JavaScript. Which is used in JS to Concatenate/join two data like variable and String data or multiple Variables in JS.
Basically it Allows/Join string and Variable at one line. If we write string and Variable without This + Concatenation sign in Code
document.write("string value " variable1);
You will face error like

Uncaught SyntaxError: missing ) after argument list
in the Console log Tag.
To prevent your program from that error and joint string and variable we have to write 2 document.write() JS attributes (one for the String data and other one for the Valribale data) or we can join then using JS + Concatenation sign.

Variables in JS (Number)

Number in Variable Example


<html>
 <head>
  <title>Numbers Variables in JS</title>
 </head>
 <body>

   <script type="text/javascript">

     var phoneNo1=1112224;
     var phoneNo2=9992234;
     var phoneNo3=9994444;

     document.write(phoneNo2+" is my 2nd Phone Number <br/> and 3rd ="+phoneNo1 +" and 1st ="+ phoneNo3);
   </script>

 </body>
</html>	

Results


Variables in JS (Boolean)


<html>
 <head>
  <title>Boolean Variables in JS</title>
 </head>
 <body>


   <script type="text/javascript">

     var a=true;

    if(a==true){
       document.write("Variable A is True");
       }
    else{
       document.write("Variable A is False");
       }
   </script>
 </body>
</html>	

Results

Boolean data is basically used for storing TRUE or FALSE value for we can show output according to those values. Here i have to use IF ELSE Condition if you want to know about HTML Conditions Like IF ELSE Conditions Click Here.

Types of Variables :

We know that JS Variables can store 3 Types of Data (Numbers,Strings,Boolean Data) but There Is Two Type of Variables in JavaScript.

1. Local Variable

2. Global Variable


1. Local Variable

Local variables are those variables who cab be accessed Locally. Variable with limitations Like Variable inside a Function ( to know about Functions click here).
So that's variable can be accessed inside the Local Function.

Local Variable Example


<html>
 <head>
  <title>Local Variables in JS</title>
 </head>
 <body>


   <script type="text/javascript">

    myname();

    function myname(){
      var name="ProgrammingHead";
      document.write("inside = "+ name);
    }

     document.write("outside = "+ name);

   </script>
 </body>
</html>	

Results

myname()

in JavaScript we have to Write function name like (myname();) in order to run a function. learn more about functions Click here.


In this Example i Have created a Variable called name inside a function called myname(). So by retrieving data from inside myname() function (document.write("inside = "+ name);) we have our Variable data in Results but retrieving the same data from same Variable from outside myname() function we have empty variable Value.
Because that variable was a Local Variable. so Local variable data can be Accessed Locally.

Global Variable :

Global Variable are like most of the Variable used for storing Values but Global Variable's data can Be accessed Globally in a Program.
Basically Declare some Variables at the Beginning/Header part in the Program and outside any Function. By doing that Variable can be Accessed Globally (Accessed inside and Outside of any Function).

Global Variable Example


<html>
 <head>
  <title>Global Variables in JS</title>
 </head>
 <body>


   <script type="text/javascript">

    var name="ProgrammingHead";
    myname();
    function myname(){
      document.write("inside = "+ name);
    }

     document.write("outside = "+ name);

   </script>
 </body>
</html>	

Results

JavaScript Tutorial 3 : JavaScript Variables

JavaScript Functions :

Functions are the part of fundamental building blocks in JS. A function is a JavaScript procedure(a set of statements that performs a task or calculates a value). To use Functions in JavaScript we have to Define a function inside JavaScript file or inside HTML's <script> ... </script> Script Tag and call that function to perform a specific Task.

Function Declarations :

For Declaring/Defining a Function in JavaScript we have to Define function keywords followed by :
function name,
parameters enclosed in parentheses (parameter) and
JavaScript Code/Statement inside Function's curly braces {..}

JavaScript Function Syntax :-

JavaScript Function Syntax :


function function_name(argument) {
		JavaScript code...
	}

Function calling/Invocation

The JavaScript code Written/Declared inside the function will execute only when "something" invokes/calls the function. Simply to run or Execute functions Data we to to call the function first.
But how to call a JavaSCript Function?

Calling/Invoking JS Function :

There are many ways to Call/Invoke JavaScript function like:

1. Calling/Invoking by Click Event.

2. Calling/Invoking by JavaScript Code.

3. Calling/invoking JavaScript Function Automatically.

1. Calling/Invoking a Function by Click Event :

Calling/Invoking a JavaSCript Function by Click Event is very simple. You just have to target any HTML Element and by using onClick="" attribute we can run any JavaScript by clicking any HTML Element/Button.
we have to just specify our HTML onClick="" attribute in the Starting tag and JavaScript Functions name in onClick="" attributes double quotes.

Calling/Invoking a Function by Click Event Example


  <button onClick="myFunction();"></button>

   <script type="text/javascript">
     function myFunction(argument){
        JS Code...
     }
   </script>

2. Calling/Invoking a JS Function by JavaScript Code :

To Call/Invoke JavaScvript Function using JavaScript code we only have to write our function name and right after function name Parenthesis () and inside pare you can assign argument values like myFunction(2);.
Simply Write your function's name and then parentheses/braces () and terminate the line using semicolon ; .

Calling/Invoking by JavaScript Code Example


   <script type="text/javascript">
     
     myFunction();

     function myFunction(argument){
        javaScript code ....
     }

   </script>	

3. Calling/invoking JavaScript Function Automatically.

If you don't want to Call a function using a Click Event or using JavaScript code and you just want to do this Calling process in a More Easy / Short way and kind of Automatic way then you just have to write / Declare your whole function inside these () parenthesis and at the end again parenthesis and terminate code using semicolon. ;
This will call and Declare your function at same time and will runs your Function Automatically.

Calling/invoking JavaScript Function Automatically Example


   <script type="text/javascript">

     (function myFunction(argument){
        javaScript code ....
     })();

   </script>		

Function Return Method

This Return method used Inside JavaScript Functions to return some values and when code reaches the Return statement, function will stops Executing. So keep in mind if you want to return any value through function then Declare this Return method at the End otherwise function's codes after the Return method will be ignored.

Return method Example


  var a = myFunction(2,3);
  
  function myFunction(x,y){
    return x+y;
  }

  document.write("value of a = " +a);

Results


Arithmetic Operations in JavaScript Functions

Arithmetic Operations like addition, subtraction, multiplication, division and ETC can we created using JavaScript Function (for more JavaScript Operation Tutorial Click here).
We have to know about some Arithmetic Operators :
addition (+),
subtraction (-),
multiplication (*),
and division (/).

Arithmetic Operations in JavaScript Functions Example


<html>
 <head>
  <title>Local Variables in JS</title>
 </head>
 <body>

   <button onClick="addition(6,2);">Addition</button>
   <button onClick="subtraction(6,2);">subtraction</button>

   <script type="text/javascript">

    var sum,sub;

    function addition(a,b){
     sum= a + b; 
     document.getElementById('result-para').innerHTML=a+"+"+b+"= "+sum;          
    }

    function subtraction(a,b){
     sub= a - b; 
     document.getElementById('result-para').innerHTML=a+"-"+b+"= "+sub;         
    }

   </script>
 </body>
</html>	

Results

Results will be Here


About the Example :

button <button> ... </button>

Button Tag to create a Button for Click Events like onClick=""

onClick Method <button onclick="function()">

onClick Method to run a Function on the Click Event.

Variables var sum,sub;

Variable to store numbers addition and subtraction values. and sum is a variable name for storing Numbers Additions and sub for Numbers subtraction Values.

JavaSCript function function addition(){...}

JavaScript Function with Addition function name with JavaScript code to Add two numbers (a and b) and giving Output in the P (ParaGraph) Tag.

Addition sum=a+b;

Using Addition's Parameter + we are Adding two number a+b and storing the Value in the Variable called sum (sum=a+b).

document.getElementById(IdName).innerHTML=variable;

This document.getElementById(IdName) Method will select the HTML Element by ID Name and .innerHTML export the Given Variable Values to the Selected HTML Element.

Concatenation a+"+"+b+"= "+sum

Concatenation to join Variable and String Value at Single sine. Where a will export our First Arguments value (which is 6) and + sign will concatenates the First Arguments value with string + like (6+) and again Concatenation will export the 2nd Argument's value (which is 2) and another Concatenation will export equal sign as string like (6+2=) and at the end Concatenation method will export the Variable with Result's Value like (6+2=8).

onclick="addition(6,2);"

Here on Click method/Attribute will run the given Function on Click and here we have Given function addition(6,2); with 2 values (6,2) six and two, where 6 is the value for First argument a and 2 is for the 2nd Argument b.

JavaScript Tutorial 5 : JavaScript Arithmetic Operations

Arithmetic Operations :

Arithmetic Operators takes numeric value as their Operands and returns a single value in results.

Operand Operator Operand Result
2 + 5 = 7

Standard Arithmetic Operators :

There are Four standard Arithmetic Operators :

1. Addition Operator (+),
2. Subtraction Operator (-),
3. Multiplication Operator (*) and
4. Division Operator (/).

Addition Operator (+) :-

Addition Operator add two or more numeric Operands and gave Total value in Result.
LIKE 2+3=5
In JavaScript we can create Variables to store our Numeric Value (Operands) and then use those value by Calling JavaScript Variables or we can directly use our Numeric Operands and Arithmetic Operators in the same line without using JavaScript Variables.

Addition Operation (without using JS Variables) :


   document.write(2+6);

Results :

Addition Operation (using JS Variables) :


   var a,b,c;
   a=2;
   b=6;
   c=a+b;
   document.write(c);

Results :


Subtraction Operator (-) :

Subtraction Operators can subtract two or more Numeric Operands and gave results in Numeric Data.
Like : 5-2=3
Here 5 and 2 is Numeric Operands and - is JavaScript Subtraction Operator and 3 is our Result.

Subtraction Operation (without using JS Variables) :


   document.write(7-2);

Results :

Subtraction Operation (using JS Variables) :


   var a,b,c;
   a=7;
   b=2;
   c=a+b;
   document.write(c);

Results :


3. Multiplication Operator (*) :

Multiplication Operator Multiply the two or more Numeric Operands and gave us result in numeric Value.
Like : 3*2=6
Here 3 and 2 is our Operands and * is JavaScript Multiplication Operator and 6 is Result of two Operands (3 and 2).

Multiplication Operation (without using JS Variables) :


   document.write(7*2);

Results :

Multiplication Operation (using JS Variables) :


   var a,b,c;
   a=7;
   b=2;
   c=a*b;
   document.write(c);

Results :

Division Operator (/) :

Division Operator Divide the two or more Numeric Operands and gave us result in numeric Value.
Like : 6/2=3
Here 6 and 2 is our Operands and / is JavaScript Division Operator and 3 is Result of two Operand's Division (3 and 2).

Division Operation (without using JS Variables) :


   document.write(6/2);

Results :

Division Operation (using JS Variables) :


   var a,b,c;
   a=6;
   b=2;
   c=a/b;
   document.write(c);

Results :


Remainder Operator (%) :

Remainder Operator returns the reminder value from two Operand values Division.
7%2=1
Here 7 and 2 is our Operand Values and % is our Remainder Operator and 1 is our value remained after the Division.

Example


   document.write(9%2);

Results


Exponentiation Operator (**) :

Exponentiation Operator retures the Value of two or more Operands where 2nd Operand become the power of first Operand.
LIKE : 2**3=8
explained : 23=8 (here 23 means we have to multiply 2 tree times like 2*2*2)
where 2 and 3 is our Operands and ** is our Exponentiation Operator and 8 is our Result.

Exponentiation Example :


   document.write(2**3);

Results :

Increment Operator (++) :

Increment Operator adds one value to our Variable or Numeric value.
LIKE: 5++ = 6
Here 5 is our Operand and ++ is our Increment Operator and 6 is our Operant value after increment. But here is two types of Increment Operators

postFix Increment Operators (a++):

postFix Increment Operators returns the Incremented value after the Execution.
so if store value like :
var a=5;
var b=a++;
Then in that variable the JavaScript program will store the value first in the Variable called b and after that program will increment the value of variable called a.
so var b=a++; result b=5; That's why we will have 5 in our variable called a because of Post Increment increment.

PostFix Increment Operator Example :


  var a,b;
  a=5;
  b=a++;
  document.write(" a="+a);
  document.write(" b="+b);	

Results :

NOTE : Hare + sign is JS Concatenation Method for joining String and Variable data.

preFix Increment Operators (++a):

preFix Increment Operators returns the Incremented value before the Execution.
so if store value like :
var a=5;
var b=++a;
Then in that variable (variable b) the JavaScript program will store the value for a (which is 5) and then for b JS program will increment the value of Variable a (++a) and after the Increment JS Program will store the increment value of Variable a in to the Variable B.
so var b=++a; result b=6; That's why we will have 6 in our variable called b because of Pre Increment.

PreFix Increment Operator Example :


  var a,b;
  a=5;
  b=++a;
  document.write(" a="+a);
  document.write(" b="+b);	

Results :

NOTE : Hare + sign is JS Concatenation method for joining String and Variable data.

Decrement Operator (++) :

Decrement Operator deduct one value to our Variable or Numeric value.
LIKE: 5-- = 4
Here 5 is our Operand and -- is our Decrement Operator and 4 is our Operant value after Deduction. But here is two types of Decrement Operators

postFix Decrement Operators (a--):

postFix Decrement Operators returns the Decrement value after the Execution.
so if store value like :
var a=5--;
Then in that variable the JavaScript program will store the value first in the Variable called a and after that program will Decrement the value.
so var a=5--; result a=5; That's why we will have 5 in our variable called a because of Post Decrement.

POSTfix Decrement Operator Example :


  var a,b;
  a=5;
  b=a--;
  document.write(" a="+a);
  document.write(" b="+b);	

Results :

NOTE : Hare + sign is JS Concatenation Method for joining String and Variable data.

preFix Decrement Operators (++a):

preFix Decrement Operators returns the Deducted value before the Execution.
so if store value like :
var a=5;
var b=--a;
Then in that variable (variable b) the JavaScript program will store the value for a (which is 5) and then for b JS program will Decrement the value of Variable a (++a) and after the Decrement JS Program will store the Decremented value of Variable a in to the Variable B.
so var b=--a; result b=4; That's why we will have 4 in our variable called b because of Pre Decrement.

PreFix Decrement Operator Example :


  var a,b;
  a=5;
  b=--a;
  document.write(" a="+a);
  document.write(" b="+b);	

Results :

NOTE : Hare + sign is JS Concatenation method for joining String and Variable data.

Arithmetic Operations in JavaScript Example


<html>
 <head>
  <title> Arithmetic Operations </title>
 </head>
 <body>

   <script type="text/javascript">

    var a,b,sum,sub,multi,div,rem,postInc,preInc,postDec,preDec,expon;
    a=7;
    b=4;
    sum=a+b;
    sub=a-b;
    multi=a*b;
    div=a/b;
    rem=a%b;
    postInc=a++;
    preInc=++a;
    postDec=a--;
    preDec=--a;
    expon=a**b;   

    document.write("Addition A + B ="+sum);
    document.write("<br/>Subtraction A - B ="+sub);
    document.write("<br/>multiplication A * B ="+multi);
    document.write("<br/>Division A / B ="+div);
    document.write("<br/>Remainder A % B ="+rem);
    document.write("<br/>PostFix Increment A++ ="+postInc);
    document.write("<br/>PreFix Increment ++A ="+preInc);
    document.write("<br/>PostFix Decrement A-- ="+postDec);
    document.write("<br/>PreFix Decrement --A ="+preDec);
    document.write("<br/>Exponentiation A**B"+expon);

   </script>
 </body>
</html>	

Results


JavaScript Tutorial 6 : JavaScript Conditional Statements

JavaScript Conditional Statements :

Conditions Statements are used to perform different actions according to given condition. For example : i want to buy a Product called "Samsung USB Flash Drive" and there is two available shops near my House who sells products like USB Drives. So i went to the First shop but i can't find my product called "Samsung USB Flash Drive" in the First shop then i have to go to the 2nd shop to buy that product.
so you can take JavaScript Conditional as my previous Example, where 2 available shops are the two different Conditions and product is the Condition, so if my product is available or my condition is true at first Statement then i can skip 2nd shop or 2nd statement, but if my product or my condition is false at first shop or 1st statement the i have to go for 2nd shop or 2nd statement.

JavaScript Conditions :

In JavaScript we have two Different Conditions :-
1. If Condition
2. Else Condition.

The if Statement (if(){....}) :-

In the IF statement we provide Condition inside IF's parentheses (condition) and JavaScript Program execution will depend on the given Condition.
if the given Condition return true then code inside the IF's Braces {code} will be executed or if Condition return false then JS program will ship the IF Statement's part/Code.

IF Statement Syntax:


   if(condition){
     JS code...
   }

IF Statement Example:


<html>
 <head>
  <title> IF statement </title>
 </head>
 <body>

   <script type="text/javascript">

    var a=10;
     
    if(a==10) {
      document.write("a is = 10");
    }

   </script>
 </body>
</html>

Result


single = vs double == :

single = assigns value to data Types like a=10;
Double == used to describe that data is equal like a==10 thats mean a is equal to 10 but this is not assigning any value to the Variable a. if variable is equal to 5 then a==10 condition will be false, but if variable a value is 10 and we are using single a=5 then it will reassign value to our variable.

Else Statement :

Else Statement specify another or alternative code to be Execute when IF Condition is false.
Normally JS Program checks IF condition true or false, if condition is True the program will Execute IF Statement's Data or IF the IF Statement's condition is false then Program will skip the IF Statement's code.
But Else statement specify another or alternative code when IF Statement condition is false.
Else Statement Executes only when the IF Statement is False that's why we don't have to gave condition in else Statement.

Else statement Syntax :


   else{
     JS Code....
   }

Else statement Example :


<html>
 <head>
  <title> Else statement </title>
 </head>
 <body>

   <script type="text/javascript">

    var a=5;
     
    if(a==10) {
      document.write("a is = 10");
    }
    else{
      document.write("a is not = 10");
    }

   </script>
 </body>
</html>

Results :


else if Statement : ( else if(){...} ) :

If we use only IF and Else statement inside out JS Program, then out program will only take one condition at a time, but using else if statement we can add multiple conditions in JS Program.

else if Syntax


    if(condition 1){
     js Code..
    } 

    else if(condition 2){
     js Code..
    }

    else{
    JS Code
    }

else if Statement Example


<html>
 <head>
  <title> If Else statement </title>
 </head>
 <body>

   <script type="text/javascript">

    var a=5;
     
    if(a==10) {
      document.write("a is = 10");
    }
    else if(a==5) {
      document.write("a is = 5");
    }
    else{
      document.write("a is not = 10 and 5");
    }

   </script>
 </body>
</html>

Results

JavaScript Comparison Operators :

Comparison Operators are used in JavaScript and in other Programming Languages to get equality or difference between variables or values.

Operator Description Example
== equal to a==1
!= not Equal a!=2
> greater then a>b
< less then b<a
>= greater then or equal a>=1
<= less then or equal a<=10

Equal to Operator ( == ):

Equal to Operator ( == )compares two values and return True and False values, If given value is equal to compared value then operator will return True or if given value is not equal to compared value then Operator will return False.

Equal to Operator


    var a=6;

    if(a>5){
      document.write("a is greater then 5");
    }
     else{
      document.write("a is not greater then 5");
    }

Results :

Not equal to Operator ( != ) :

Not equal to div compares two value and return True and False value. If value is not equal to another value then the Operator will returns True and if given value is equal to another value then Operator will return False.

Not equal to Operator


    var a=6;

    if(a!=5){
      document.write("a is not = 5");
    }
     else{
      document.write("a is = 5");
    }

Results


Greater Then Operator (>) :

Greater the Operator compares two value and return that variable or value who is greater then other variable or value.

Greater Then Operator:


    if(5>2){
      document.write("5 is greater then 2");
    }
      else{
      document.write("2 is greater the 5");
    }

Results :


Less Then Operator (>) :

Greater the Operator compares two value and return that variable or value who is Less then other variable or value.

Less Then Operator:


    if(2<5){
      document.write("2 is less then 5");
    }
      else{
      document.write("5 is less then 2");
    }

Results :


greater then or equal to ( >= ):

This operator compares two value for 2 things, 1st value is greater or not and 2nd value is equal or not and if value is greater then operator will return true and if value is not greater then but equal to another variable/value then also operator will returns True but if variable/value is not greater and also not equal to another value/variable then operator will return False

greater or equal operator :


    if(7>=7){
      document.write("7 is greater or equal to 7");
    }
      else{
      document.write("7 is not greater and equal to 7");
    }

Results :

Here 7 is not greater then 7 but 7 is equal to 7. Program will reacts the same for less or equal to Operator, if value/variable is less or equal to another value/variable then operator will returns TRUE.


Logical Operators :

Logical operators determines logical deference between two variables/values

Operator Description Example
&& And (7>5 || 7<10)
|| or (2>5 || 2<3)

And Operator ( a<5 && a>10 )

And Operator compares two value for two different given conditions at the same time and if both of the given Condition are true then Operator will returns True and if one of the 2 condition or both given conditions are false the Operator will return False.

And Operator :


    var a=7,b=5;
    if(a>b && a!=b){
      document.write("Variable a is greater and not equal to Variable B");
    }
      else{
      document.write("a is not greater or equal to B");
    }	

Results :

Or Operator (a>b || a<b):

Or Operator compares two value for 2 Conditions, if one of the two condition or both conditions return true then Or Operator Return True but Or operator will only returns False if both Conditions return false.

Or Operator :


    var a=7,b=5;
    if(a>b && a==b){
      document.write("Variable a is greater or equal to Variable B");
    }
      else{
      document.write("a is not greater and equal to B");
    }	

Results :

If Else Statement Example


<html>
 <head>
  <title> JavaScript If Else Statements </title>
 </head>
 <body>

   <script type="text/javascript">

    var a=7,b=5,c=0;

    if(a<b && a>c){
       document.write("a is less then b and greater then c");
    }
    else if(a<b || a>c){
       document.write("a is less then b or greater then c");     
    }
    else{
       document.write("a is not less then b and not greater then c");
    }

   </script>
 </body>
</html>	

Results


JavaScript Tutorial 7 : JavaScript Arrays

JavaScript Arrays :

Array is a Special variable in JavaScript who can store multiple Values inside a single VAriable and call any Variable's value by its index Number.

Storing Values in Array :

for storing value in a Array we have to declare a special Variable (array) like (var array_name = [];) and inside the box brackets [] we have to write values for our Special Variable. We can assign numeric and String values to our Special Variable (array) and separate multiple values using single , comma.

JavaScript Array Syntax:


    var myArray = ["value1","value2","value3"];

Calling Array Value :

we can assign multiple value to a single Variable in array and for calling array Values we have to write our Array Variable name and this will export the all Array Values bu if we want to export only one array Value then we have to write array name first and then index number of the assigned value.

Array Index Number :

Array index number starts from 0 and ends according to total number of assigned values in array.

example : var my_array = ["cat","dog","cow","rat"];
var my_array = [0,1,2,3];

here at the index 0 we have cat,
index 1 we have dog,
at index 2 we have cow,
and at index 3 we have rat.

Calling JS Array Example:

Calling JS Array Example :


    var myArray = ["cat","dog","cow","rat"];

    document.write(myArray);    

Results :

Assigning Values to Array using Index Numbers :

There is a another easy and more understandable way to assign value to Array by using Index number, As we know array's index starts from 0 so the first value will have the index number of 0 and by using this method we can easily identify values bu Index numbers.
to do that we have to define a empty array like var myArray = [];
and after terminating ; the declaration line we can assign values by variable name with index numbers like myArray [0]="";.

Values using Index Number

var myArray = []; myArray[0]="cat"; myArray[1]="dog"; myArray[2]="cow"; myArray[3]="rat"; document.write(myArray);

Adding New value to Array :

to assign new value to JS Array we have to write our array name with .push method and inside the round brackets/braces we have to write new value for our Array.

Adding New value to Array Example


    var myArray=["cat","dog","rat"];

    myArray.push("cow");

    document.write(myArray);   

Results

Associative Arrays :

JavaScript not only supports array index number also support array named index. So we can store values inside array Variable by Named Index and also call that value by its Index Name.


    var myArray = [];
    myArray["firstValue"]="cat";
    myArray["secondValue"]="dog";
    myArray["thirdValue"]="cow";

    document.write(myArray["thirdValue"]);

Results

JavaScript Arrays Example

JS Arrays Example


<html>
 <head>
  <title> JavaScript Arrays </title>
 </head>
 <body>

   <script type="text/javascript">

    var cars = [
     "Lamborghini",
     "Ford",
     "Ferrari",
     "Bugatti ",
     "Koenigsegg"];

     cars.push("Aston Martin");

     var totalCars=cars.length;

     document.write("my all cars ="+cars);
     
      document.write("<br/>Total cars Names ="+totalCars);

     document.write("<br/>my car at index 2 is ="+cars[2]);

     document.write("<br/>new added car ="+cars[totalCars-1]);

   </script>
 </body>
</html>	

Results

JavaScript Loops :

Loops are used in JavaScript to perform a Task Continuously without Declaring That task multiple times. Loops can run a task multiple time or According to Given conditions.
So there 3 Different Loops in JavaScript Like :
1. While Loop,
2. Do while Loop,
3. For Loop.

1. While Loop :

While loop Depends on the given Condition and executes the Declared data inside While loop as long as condition is True.

So when we run our program Compiler will treat our while Loop according to the Given Condition, So if the condition is true then program will execute the Code from while loop and after Executing while loop's code then again Compiler will go back and check the Condition again and if the Given condition is still true then Compiler will execute the Code again until condition return False.
Condition Statement

while Loop JavaScript

While Loop Syntax:


    while(condition){
      statement.....
    }

Printing numbers 1 to 10 :

Without Loop if we want to print Numbers form 1 to 10 then we have to write number 10 times and expert/print that number by using document.write() or other printing methods.
But using While Loop we can print numbers from to 10 by declaring a single print method inside While loop and set while loop condition so we can execute while loops code/statement 10 times.

While Loop Example:

While Loop Example :


<html>
 <head>
  <title> While Loop Example </title>
 </head>
 <body>

   <script type="text/javascript">

    var a=1;

    while(a<=10){
      document.write(a+"<br/>");
      a++;      
    }

   </script>

 </body>
</html>	

Results :

Example Explained :

script tag <script> :

Script tag used inside HTML Document to insert/Declare JavaScript code. and also using this <script;> tag we can include or link External .js file by using src="" attribute.

Variable var:

by using var we declare Variables inside JavaScript file/Code so we can store and call value from that variable name.

while Loop while(condition){code..}

while loop to run our statement multiple times according to given Condition.

while(a<=10):

In while loop's condition we have a<=10 that's mean our loop will run until a is less the 10 or a is equal to 10 (a<=10).

While(){statement..}

In while Loop's Statement we have two Statements

document.write(a+"<br/>")

document.write() method will print the value in the Output screen , where given values are a+"<br/> which mean a will print the value of Variable a and + will concatenate/join our string value ("<br/>) with out variable (a) and "<br/>" will add a line break after every number 1 to 10.

a++ Increment:

Here i have used JavaScript Increment method to increment the Variable a values by 1 every time While loop Executes.

+ Concatenation

this + Concatenation method helps Join string data with variables. in the output method we have used this + Concatenation method to join Variable a value with string <br/> which is a HTML tag to add Break Line.


Do While Loop:

Do While loops works the same as While loop but here we Declare our Statement first inside do and out condition after the Statement in while. As I've already said, Do While works the same as While loop, it will check given Condition first before Executing give Statement.

do while Loop JavaScript

DO While Loop Syntax


    do{
      statement...
      }while(condition);

Do While Loop Example


<html>
 <head>
  <title> Do While Loop Example </title>
 </head>
 <body>

   <script type="text/javascript">

    var a=1;

    do{
      document.write(a+"<br/>");
      a++;      
    }while(a<=5);

   </script>

 </body>
</html>		

Results


For Loop :

For loop Also works the same as other JavaScript Loops like While and Do while loop, but the Declaration part is little Different and handy here.
in other loops we have to declare variables first and the we have to apply increment or Decrement before or after our Statement and in the condition section we can only Define condition like variable is greater or less then, equal, not equal etc.
But in For loop we can Declare variable or assign value, condition (<,<=,>,>=,==) and Increment or Decrement variable at one line.

for Loop JavaScript

for Loop Syntax


    for(init,condition,increment){
      statement.....
    }   

For Loop Example


<html>
 <head>
  <title>For Loop Example </title>
 </head>
 <body>

   <script type="text/javascript">
   
   for(var num=1; num<=5; num++){
   
   document.write(num+"<br/>");

   }

   </script>

 </body>
</html>	

Results

javascript loop through array :

By ruining JavaScript through Array can export every data present inside that array without declaring/printing the value multiple time.
Using array we can print or Export every Value that's stored inside that Array by declaring once inside single Loop.
if we have array of 2 to 10 values then we can easily print each value by declaring print statement/method for each (2-10) values.


    var myArray=["value1","value2"];
    document.write(myArray[0]);
    document.write(myArray[1]);

But if we have huge amount of value like 100 plus values inside one or more then one array then its became too hard to print every value by declaring print method for each array value. in those cases array saves out time.
But before Looping array data we have to know about JavaScript loops and JavaScript arrays.

Full Tutorial about JavaScript Arrays
Full Tutorial about JavaScript Loops

JavaScript Arrays :

Array is a Special variable in JavaScript who can store multiple Values inside a single VAriable and call any Variable's value by its index Number.

Storing Values inside JavaScript Arrays :

To store values inside we have to write our values (numeric or string) between Box brackets [ ] and and separates values using comma ,.

Calling Array Values :

To call array values we have to write our name inside JS write method .write(myArray); to print All values present inside a Array, and if we want to print a single value from any JS array then we can call that value using it's index number myArray[0].

Array in JavaScript :


    var myArray=["value1","value2"];
    document.write(myArray);    
    document.write(myArray[1]);

JavaScript Loops :

Loops are used in JavaScript to perform a Task Continuously without Declaring That task multiple times. Loops can run a task multiple time or According to Given conditions. So there 3 Different Loops in JavaScript Like : 1. While Loop, 2. Do while Loop, 3. For Loop.
Note : in this tutorial we are only going to use for loop to print array value, but if you want to know about other while and do while loops also then you can check my Full Tutorial by clicking here about JavaScript Loops.

For Loop :

In for Loop out program will check the Condition first so if the given Condition is True the out program will precess our given statement/code declared inside for loop and if Condition is False the program will skip the Statement/code declared inside for loop and returns the Value.
in for loop we have to define 3 things
1.init,
2.condition,
3.and increment or decrement.
Note : we will understand these things after the Last Example (javascript loop through array Example).

for Loop JavaScript

for Loop Syntax


    for(init,condition,increment){
      statement.....
    }   

For Loop Example


<html>
 <head>
  <title>For Loop Example </title>
 </head>
 <body>

   <script type="text/javascript">
   
   for(var num=1; num<=5; num++){
   
   document.write(num+"<br/>");

   }

   </script>

 </body>
</html>	

Results

javaScript loop through array:

javaScript loop through array is a process to print/Export or Process Array's data using Loop. So we can declare our array once inside a loop and export every data present inside that Array.

javaScript loop through array Example :

javaScript loop through array Example :


<html>
 <head>
  <title>For Loop Example </title>
 </head>
 <body>

   <script type="text/javascript">

   var myArray=["cat","dog","cow","rat","parrot","rabbit","snake"];
   
   for(var indNo=0; indNo < myArray.length; indNo++){
   
   document.write(myArray[indNo]+"<br/>");

   }

   </script>

 </body>
</html>	

javaScript loop through array Results

Example Explained :

script tag <script> :

Script tag used inside HTML Document to insert/Declare JavaScript code. and also using this <script;> tag we can include or link External .js file by using src="" attribute.

Variable var:

by using var we declare Variables inside JavaScript file/Code so we can store and call value from that variable name.

for Loop for(init;condition;increment){code..}

for loop used in Example to run our statement/code multiple times according to given Condition.

var indNo=0:

Here inside for loop we have Declared a Variable using var called indNo (IndexNumber) and assign 0 as its value. Because we are going to use this Variable at the place of Array's index number.

indNo<myArray.length

using indNo<myArray.length inside for loop we have set our Condition for that loop, where myArray.length will get the Array's value Length from the Array Named myArray and return the total length of values inside that Array. and whole condition will be true until variable indNo is less then myArray.length array Length.

indNo++

this ++ Concatenation method will increment the Variable's (indNo) value by one every time after Condition return true and Executes the Statement.
That will assign index number index number 0 to 6 to Array at document.write() statement.

document.write(myArray[indNo]+"<br/>")

document.write() method will print the value in the Output screen , where given values are myArray[indNo]+"<br/> which mean myArray[indNo] will print the value of Array at index number of indNo variable value, which will change according to for loop Condition, + will concatenate/join our string value ("<br/>) with out variable (a) and "<br/>" will add a line break after each array Values in the Output.

Comments

download minecraft pc

http://tinyurl.com/y2lomfwl
01:31 am

I like the helpful information you provide in your articles. I'll bookmark your blog and check again here frequently. I'm quite sure I'll learn lots of new stuff right here! Best of luck for the next!

download minecraft pc

http://tinyurl.com/y2pnhs64
08:09 am

Pretty part of content. I simply stumbled upon your web site and in accession capital to claim that I acquire in fact loved account your blog posts. Anyway I'll be subscribing in your feeds and even I success you get admission to persistently fast.

how to download minecraft free

http://tinyurl.com/y3mw7jqs
05:17 pm

What's Happening i am new to this, I stumbled upon this I've found It positively helpful and it has aided me out loads. I am hoping to give a contribution & assist other users like its aided me. Great job.

g

http://j.mp/2W3j1qB
11:25 am

Hi there! Someone in my Myspace group shared this site with us so I came to check it out. I'm definitely loving the information. I'm book-marking and will be tweeting this to my followers! Fantastic blog and wonderful style and design.

g

http://tinyurl.com/y3zh6m87
02:45 pm

My brother suggested I might like this web site. He was entirely right. This post truly made my day. You cann't imagine simply how much time I had spent for this information! Thanks!

minecraft download mojang

http://tinyurl.com/y3zhtk7b
06:50 pm

We stumbled over here from a different website and thought I should check things out. I like what I see so now i am following you. Look forward to checking out your web page for a second time.

g

http://tinyurl.com/y25huum7
10:48 pm

Wow, that's what I was looking for, what a information! existing here at this weblog, thanks admin of this web site.

minecraft free download

http://tinyurl.com/y4n372uc
04:52 am

Very quickly this web page will be famous amid all blog users, due to it's good posts

minecraft download pc

http://tinyurl.com/y4abb95v
02:51 pm

You really make it appear so easy together with your presentation but I to find this matter to be really one thing which I feel I'd by no means understand. It kind of feels too complex and extremely wide for me. I'm taking a look ahead to your next post, I'll attempt to get the cling of it!

minecraft pc download

http://j.mp/2LpECFj
10:03 am

This is a topic that is close to my heart... Thank you! Exactly where are your contact details though?

download minecraft free

http://tinyurl.com/yy5nerzp
05:00 am

Awesome blog! Do you have any helpful hints for aspiring writers? I'm planning to start my own website soon but I'm a little lost on everything. Would you propose starting with a free platform like Wordpress or go for a paid option? There are so many choices out there that I'm completely confused .. Any tips? Many thanks!

gamefly

http://t.co/5RBfBO3Vyn
02:14 pm

Wow, this paragraph is nice, my younger sister is analyzing such things, so I am going to tell her.

gamefly free trial

http://j.mp/2Lf197O
08:13 pm

Wow, awesome blog layout! How long have you ever been running a blog for? you made running a blog glance easy. The whole look of your web site is fantastic, as neatly as the content!

gamefly free trial

http://t.co/YDtjqLPAhw
07:38 pm

I visited multiple blogs but the audio quality for audio songs current at this web page is in fact wonderful.

gamefly free trial

http://tinyurl.com/y3ej38dl
02:25 pm

I am regular reader, how are you everybody? This paragraph posted at this website is genuinely nice.

minecraft

http://bit.ly/2CwylAH
08:48 pm

I savor, lead to I discovered just what I used to be having a look for. You've ended my 4 day lengthy hunt! God Bless you man. Have a great day. Bye

minecraft

http://tinyurl.com/yxam789p
07:49 pm

naturally like your web site but you have to check the spelling on several of your posts. Many of them are rife with spelling issues and I to find it very bothersome to inform the reality nevertheless I'll surely come back again.

http://tinyurl.com

http://tinyurl.com/yyxmoq35
01:08 am

We're a bunch of volunteers and starting a brand new scheme in our community. Your site provided us with useful info to work on. You've performed a formidable process and our whole community might be grateful to you.

minecraft

http://tinyurl.com/y3hqv9xr
01:33 pm

Your style is very unique in comparison to other folks I've read stuff from. Many thanks for posting when you have the opportunity, Guess I'll just book mark this blog.

minecraft

http://tinyurl.com/yy662sfn
05:30 am

Hello! This is my first comment here so I just wanted to give a quick shout out and say I really enjoy reading your articles. Can you suggest any other blogs/websites/forums that go over the same topics? Thanks for your time!

minecraft

http://j.mp/2CwylAH
04:15 am

It's in fact very complicated in this busy life to listen news on Television, therefore I simply use web for that reason, and get the hottest news.

minecraft

http://j.mp/2EUmVZf
10:42 am

I'm extremely impressed with your writing skills and also with the layout on your weblog. Is this a paid theme or did you modify it yourself? Anyway keep up the excellent quality writing, it's rare to see a nice blog like this one today.

acuity

https://b2stats.com/
02:41 pm

I used to be suggested this website via my cousin. I'm not sure whether or not this post is written through him as no one else understand such specific about my difficulty. You're wonderful! Thanks!

Admin

Thanks.It means a lot to Us.

Write to Us