Monday, 17 February 2020

JAVASCRIPT

JAVASCRIPT

JavaScript ---Uniqueness

                                     


                         User Interface (UI)                                        Back End
                          DOM                                                           API -   DB
                        JS Engine                                                   Node JS – Node(platform)   
                      Browser--Chrome(V8)                                      JS Engine-(V8)
                                     Firefox(Spider Monkey)                    Terminus/Console
                                     Internet Explorer(Chakra)                                                             

Key points/ Rough work - Html to DOM conversion---parses.
Object - Is nothing but property and methods/functions.
CSS - apply for paragraphs and tags etc. changes before page submission.
JS - apply for paragraphs and tags etc. changes after page submission also.

(1) In the above diagram
(A) We can use JS in client side with the help of DOM tree, Browsers, JS Engines.
(B) We can use JS in server side has Node JS with the help of JS Engines and terminus/consoles.
(2) We have to seen how to create a webpage and how to place html elements like tables, images, forms etc. on the top of the webpage and also we have seen how to add style and responsive nature to the html elements.
(3) Now onwards we are going to look at behind the webpage how to interact with html elements which are on the top of the webpage with some scripting code which is in behind the page.
(4) In order to gives dynamic nature or interact with html elements with JavaScript language.
JavaScript programming language has nearly 25 years history. In earlier days JavaScript is used only for client side scripting purpose.
(5) But now a day JS is also using on server side scripting this brings huge change in development of web applications.

Using JavaScript with DOM trees: - Document Object Model (DOM) is a platform or language neutral interface. This allows JS to modify or delete or add content to html elements. DOM converts all html elements into objects. Object contains property and methods. In JS document object is most commonly used object. This document object contains various kinds of methods to manipulate the DOM elements content.
getElementById() method is the most commonly used method in JS. With the help of script tag here provide JS code to html page. We can place script tag in body section or header section depending on context.
With the help of event attributes we can active/invoke the functions which are in JS files.

Example1: -

Example1.html: -

<html>
<body>
    <h1 id="a">Welcome to JAVASCRIPT</h1>
<button type="button" onclick="red()">Display_In_Red</button>
<button type="button" onclick="green()">Display_In_Green</button>
<script src="Example1.js"></script>
</body>
</html>
In the above example onclick is event attribute which is used to call functions in JS file.

Example1.js

var element=document.getElementById('a')
function red()
{
    element.style.color="red";
}
function green()
{
    element.style.color="green";
}

In the above example
document --- Parent Object,
getElementById--- Method.
var keyword which is used to define a variable.
function is also a keyword which is used to create a function.

Example2: -

Example2.html
<html>
<head>
</head>
<body>
    <input type="text" id="x">
    <button type="button" onclick="a()">Submit</button>
    <h1 id="y"></h1>
    <script src="Example2.js"></script>
</body>
</html>

Example2.js: -
var text="Welcome"
function a() {
    var name=document.getElementById('x').value;
    document.getElementById('y').innerHTML=text+name;
    document.getElementById('y').style.color="blue";
}

In the above example innerHTML is property of an object which is used to add content to html element.
style.color is also one kind of property which is used to give color to html content.

JavaScript is a syntactical programming language it means it follows set of rules and set of instructions to write a JavaScript Program.
Syntax means set of rules/ instructions and that will follow some structure.
JavaScript syntax defines 2 types of values/data
(1) Fixed values: - In order to create fixed values we have to assign data directly to html objects this is called literal approach/values.
(2) Variable values: - In order to assign values to DOM objects through variables is called variable values/approach.

JS Variables: -
Variable is a container which holds data or values. In JS in order to create a variable we use back keyword and in order to assign data to a variable we have to use assignment operator (=).
var name; //Declaration
name=”Welcome to JS”; //initialization
var name=”JS”; //Definition

JS Data types: - Data type is a most important concept in programming languages why because without data type it is very difficult to a computer to perform operations or solve below kinds of problems.
var a=”JS”+16+4; //result=”JS164”
var a=16+4+”JS”; //result=20JS

(1) JS supports data types like
number, string, Boolean (t, f), array[ ], object({}), null, undefined.
(2) In JS data types are dynamic, that means we need not to specify it data types externally. It automatically specifies data types by assigning values.

JS Operators: - JS provides some operators to perform some operations.
(1) Arithmetic operators (+, -, *, /, %)
(2) Assignment operators (=)
(3) Comparison operators (<, >, <=, >=, ==, !=)
(4) Logical operators (&&, ||, != )
(5) Conditional operators/ternary (?) This is also known as single line if else statement.
Syntax: - (condition)? value1: value2;
Example: - var (10>18)? “Yes”: “No”;

JS Functions: - Function is a block of code which is executed when something invoke/call.
In JS we use that we have to give name to a function after that we add () [() parenthesis] to pass parameters, after that we assign {} curly braces to define code/write executable statements.
Example.js: -
function sayhi()
{
Console.log(“Hi..to all”);
}
Sayhi();

In the above example we didn’t we use parameters as well return type, the above function without call function and we use console.log (“”) statement to print output on console.

JS function with parameters and return type: -

Eample.js: -
var discount=0.1;
{
return a+b;
}
var result=sum(10,20);
console.log (“total purchase:”+result);
console.log (“discount get:”+result*discount);

In the above example we passed 10 and 20 as arguments the sum function return sum of two
Products here result is a variable with stores the values which is return by some function.

(Q) What is parameterized and Non-parameterized function?
Parameterized- changes the output at an every time.
Non- Parameterized- doesn’t change the output at an every time its shows the same output at any time.

Control statements: - We are used to control the execution/ flow of program.
The main use of control statements is to optimize the code and perform actions depending on conditions.
Control statements are divided into 2 types
(1)   Conditional/ Decision making statements.
(2)   Loop/Iteration statements.
(1) Conditional Statements: - Conditional statements are used to perform different actions based on different conditions.
If, Else, Else if
If statement: - It specifies a block of code will be executed when the condition is true.
We can use if statement independently.
Syntax: -

if (condition)
{
Statements/ block of code
}

Example.js: -

function checkeven(a)
{
If(a%2==0)
{
Console.log(“Is Even number”);
}
}
checkeven(20);

(1) In the above example we used if keyword to define if statements.
(2) console.log statement is executed when the condition is true.
(3) We used == operator which is belong to comparison operator that will return true/false depending on the condition.
(4) We used % (Modules) arithmetic operator to perform arithmetic operation.

Else statement: - We use else statement to specify a block will be executed when the condition is false.
We can’t use else statement independently.
Syntax: -

if (condition)
{
Code/ statement-1 ----- true
}
else
{
Code/ statement-2 ----- false
}

Example.js: -

function checkeven(a)
{
if(a%2==0)
{
console.log(“Is Even number”);
}
else
{
console.log(“Is odd number”);
}
checkeven(23);

In the above example we used else keyword to define else statement that will be executed when that if condition is false.

Else if Statement: - We want to specify a new condition when the previous condition is false, then we go with else if statement.
 Syntax: -

if (condition-1)
{
Code/ Statement-1
}
else if(condition-2)
{
Code/ Statement-2
}
Else
{
Code/Statement-3
}

Example.js: -

function checkbigone(a,b)
{
if(a>b)
{
console.log(“a is big than b”);
}
else if(a<b)
{
console.log(“b is big than a”);
}
else
{
console.log(“equal”);
}
checkbigone (10,20);
We used else if keyword to define else if condition is used to create/add new conditions.

(2) Looping/Iteration statements: - Iteration statements are used to execute a block of code a number of times as we want. It is possible with iteration statements and also called as looping statements.
For, Do-while, while
For loop: - It is used to execute/iterate a block of code number of times as we want it means we know the number of iterations the loop will go.

Syntax: -

for(Initialization;Condition;Increment/Decrement)
{
Statements
}

Example: -
If we want even numbers up to 10 we have to iterate the loop up to 10.
for(let i=0; i<=10; i++)   //i++ can write as i=i+1
{
if(i%2==0)
{
console.log(i);
}

(1) In above example we used for keyword is define for loop.
(2) In initialization statement we used let keyword to define a variable i. let keyword provides block level scope (means we can access the variable with in the block only) to i variable and we define starting point of ‘i’ with initializing i=1;
(3) In condition statement we defined number of iterations with the help of increment/decrement statement.
(4) In for loop initialization statement executes only once when the condition is true, then loop allow to execute the inside statements.

While loop: - we use while loop to execute a block of code when we don’t know the exact iterations are required to get the output.
Syntax: -
 Initialize statements
While (condition)
{
Increment/Decrement
}

Example.js: - If we want 10 even numbers in this example we don’t know the number of iterations so we can use while loop.
let i=1;
let c=1;
while(c<=10)
{
if(i%2==0)
{
console.log(i);
c++;
}
i++;
}
console.log(i)
console.log(c)

do while loop: - It is used to execute a block of code at least one time even though the condition is true. It means do-while loop execute its body at first time after that it checks the condition if the condition is true then it allows another/further iteration else it terminate the loop.

Syntax: -
do
{

}
while (condition);

Example.js: -
let i=0;
do
{
console.log(“hi”);
i++;
}
while(i<2)

In the above example we used do keyword to define block of while loop and here we use while keyword to check condition on iterations.

for in loop: - It is used to iterate the objects.
In generally objects are two types
(1) Iterable objects (arrays, strings)
(2) Non-iterable objects (object)

We use for in loop for (objects) string and arrays that will iterate index of an above objects (string, arrays).
We use for in loop for object that will iterate property of an object.
Example: -
var obj=”abcd”;
for(let i in obj)
{
console.log(i);
}

In the above example we use string object that’s why for in loop iterated indexes.
We used in keyword to define for in loop.
Example: -
var object={
Name:”Java”,
Age:25
}
for(let i in object)
{
console.log(i+””+object[i])
}

In the above example we used an object that why for in loop iterates properties of the object.
Here i is the property of an object and we want to print value of that property we have to write like this object[i].

for of loop: - It is used only for iterable objects like arrays, strings and it iterates values of objects.
Example: -
var a=[1,2,3]; 
for(let i of a)
{
console.log(i);
}
In the above example we used of keyword to define for of loop that iterates values of an object.

Objects: - Object is a heart of JS programming language.
In general object is a real world entity like car, Bike, Chair etc.
Object has state and behavior.
Example: -
Dog
State                                              behavior
   |                                                         |
Color- black                                   Sleeping
Weight-15 kg’s                              Running
Height- 2 feet                                    Eating
State of an object has properties/data members.
Behavior of an object has actions functions/methods.
In JS we can create an object in 2 ways
(1) Literal Approach/Method—By creating an object directly.
(2) Using new keyword
Example of student entity: -

var student={
Name:”Anil p”,
Age:23,
Id:123
}
//The above code is for literal approach.

//Below code is access object properties
console.log(student.name);
console.log(student[‘age’]);

Output: - Anil p 23

The above example student is object name student name is “Anil p” that means student object contain name property and its value is “Anil p”.

We can access object properties in two ways
(1) object­_name.property_name
(2) object_name[‘property_name’]

An object also contain functions/actions in JS, we can define actions in object like below
var student={
    first_name: "Anil",
    last_name: "Babu",
    Age:28,
    fullname:function()
    {
        return this. first_name +"" +this. last_name;
    }
}
console.log(student. fullname())

Output: - Anil Babu

(1) In the above example we used function keyword to define a function but we did it mansion the name to function, this kind of functions we call anonymous function means function without function name.
(2) We used return keyword to return the output/statements.
(3) We use this keyword to represent current object property.
(4) Here in order to get fullname we used parentheses after property name. If we did it used parentheses that we will return function definition instead of result.

In JS everything is an object like arrays, strings these objects provide predefined functions to minimize the code or increase the development speed.

String: - In JS string is a group of characters and it provide some predefined functions/methods to perform an actions on strings.
Methods of string
length- We used to find out the length of the string.
trim- We used to delete the white spaces before and after the string.
touppercase- We want to convert a string into uppercase letters.
tolowercase- We want to convert a string into lowercase letters.
concat- We used to get concat two strings.

//Trim method
var a=”ab”;
var b=”ab ”.trim();
console.log(a==b)
//toupper/tolowercase
var a=”ab”;
console.log(a.touppercase());
console.log(a.tolowercase());

Arrays: - Array is an object with the help of an array we can hold ‘n’ number of homogeneous elements.
Example: -
var a=[1,2,3,4,5];   //Number
var b=[“abcd”, “bcde”, “efgh”];  //String
var c=[{name:”ab”, age:23},{name:”cd”, age:25}];    //Object

Methods of arrays
length- we can find out the length of given array.
push- we can add a new element at last index.
pop- we can remove the last element in an array.
unshift- we can add an element in starting position.
shift- we can remove the first element.
splice- we can perform multiple actions by varying arguments by depending parameters.
Syntax of splice: - splice [Starting Index, Remove Elements, Add elements];
Example: -
[1,2,3,4]
a.splice (0,1) for deleting 0 index element.[2,3]
a.splice (0,0,10) for adding 10 in 1 index.[10,1,2,3]

JavaScript Programs for Assignments

Assignment 1: -

Assignment1.html: -

<body>
        <div class="container-fluid">
                <div class=card-deck>
                    <div class="card border border primary">
                        <div class="card-header border border-primary">
                                <nav class="navbar navbar-expand-sm bg-dark navbar-blue justify-content-center">
                                        <!----<ul> Unordered list----->
                                        <ul class="navbar-nav nav nav-pills">
                                        <li class="nav-item">
                                        <a href="#" class="nav-link" data-toggle="pill"><h1>Calculator Assignment</h1>
                                        </a>
                                        </li>               
                                        </ul>
                                        </nav>
                        </div>
                        <div class="card-body border border-primary" >
                                <form>
                                        <table align="center" height="300px" >                                              
                                                    <tr>
                                                            <td><h3>First Value</h3> </td>
                                                            <td><input type="number" id="a" placeholder="Enter First Value"></td>                                                                                                                                                                      
                                                    </tr>
                                                   <tr>
                                                        <td><h3> Second Value</h3></td>
                                                        <td><input type="number" id="b" placeholder="Enter Second Value"></td>  
                                                   </tr>
                                                    <tr>
                                                        <td></td>
                                                        <td><button type="button" onclick="Sum()">+</button>
                                                            <button type="button" onclick="Sub()">-</button>
                                                            <button type="button" onclick="Mul()">*</button>
                                                            <button type="button" onclick="Div()">/</button>
                                                            <button type="button" onclick="Modul()">%</button></td>                                                        
                                                    </tr>                                               
                                        </table>
                                    </form>
                        </div>
                        <div class="card-footer border border-primary">
                            <table align="center">
                                <tr>
                                    <td>  <h4>Result is:- </h4></td>
                                    <td> <div id="result">
                                        </div></td>
                                </tr>
                            </table>                                                        
                                    <script src="CalculatorAsgn.js"></script>
                        </div>
                    </div>
                </div>
            </div>
        </body>

Assignment 1.js: -

function Sum() {
    var a=document.getElementById('a').value;
    var b=document.getElementById('b').value;
    document.getElementById("result").innerHTML=parseInt(a)+parseInt(b);
}
function Sub() {
    var a=document.getElementById('a').value;
    var b=document.getElementById('b').value;
    document.getElementById("result").innerHTML=parseInt(a)-parseInt(b);   
}
function Mul() {
    var a=document.getElementById('a').value;
    var b=document.getElementById('b').value;
    document.getElementById("result").innerHTML=parseInt(a)*parseInt(b);   
}
function Div() {
    var a=document.getElementById('a').value;
    var b=document.getElementById('b').value;
    document.getElementById("result").innerHTML=parseInt(a)/parseInt(b);   
}
function Modul() {
    var a=document.getElementById('a').value;
    var b=document.getElementById('b').value;
    document.getElementById("result").innerHTML=parseInt(a)%parseInt(b);  
}
Output: -



Assignment 2: -

Assignment 2.html: -

<body>
        <div class="container-fluid">              
                        <div class="card">
                            <div class="card-header border  text-center">
                               <h1>10% Discount on Total Price</h1>                                                                                                
                            </div> 
                            <div class="row">
                            <div class="col-1"></div>
                        <div class="col-10 card-body" >                           
                                        <table class="table table-borderless">
                                                <tr>
                                                    <th>Item Name</th>
                                                    <th>Item Price/kg</th>
                                                    <th>Quantity</th>
                                                </tr>
                                                <tr>
                                                    <td>Rice</td>
                                                    <td>50 RS</td>
                                                    <td><input type="number" id="Rice"></td>
                                                </tr>
                                                <tr>
                                                    <td>Tomato</td>
                                                    <td>30 RS</td>
                                                    <td><input type="number" id="Tomato"></td>
                                                </tr>
                                                <tr>
                                                    <td>Onions</td>
                                                    <td>60 RS</td>
                                                    <td><input type="number" id="Onion"></td>
                                                </tr>
                                            </table>
                        </div>
                    </div>
                        <div class="card-footer">
                                <div class="text-center">
                                        <button type="button" class="btn btn-primary" onclick="bill()">Genarate Bill</button>
                                </div>                                                        
                                <table class="table-borderless">
                                        <tr>
                                            <th>Amount:</th>
                                            <td id="Amount"></td>
                                        </tr>
                                         <tr>
                                            <th>Discount:</th>
                                            <td id="Discount"></td>
                                        </tr>
                                         <tr>
                                            <th>Total:</th>
                                            <td id="Total"></td>
                                        </tr>
                                    </table>
                    </div>
                </div>
            </div>                                         
            <script src="BillGeneratorAsgn.js"></script>
</body>

Assignment 2.js: -

function bill(){
    var Rice=document.getElementById('Rice').value;
    var Tomato=document.getElementById('Tomato').value;
    var Onion=document.getElementById('Onion').value;
    var Amount=50*parseInt(Rice)+30*parseInt(Tomato)+60*parseInt(Onion);
    var Discount=Amount*0.1;
    document.getElementById('Discount').innerHTML=Discount;
    document.getElementById('Amount').innerHTML=Amount;
    document.getElementById('Total').innerHTML=Amount-Discount;
}

Output: -


(Q) Write a program to find length of given string?
/*
//First Method
var a="abcde";
console.log(a.length);
*/
//Second Method
var a="abcd";
var length=0;
for(let i in a)
{
    length=+i+1;
}
console.log(length);
console.log(a);

(Q) Write a program to print reverse the given string?
function strrev(a)
{
/*
for(let i=a.length-1;i>=0;i--)
{
    console.log(a[i]);
}
}
strrev("ANIL");
*/
// using length method?
var length=0;
for(let i in a)
{
    length=+i+1;
}
for(let i=length-1;i>=0;i--)
{
    console.log(a[i]);
}
}
strrev("Suces");

(Q) Write a program to find reverse the given array?
function array(arra)
{
    var length=0;
    for(let i in arra)
    {
        length =+i+1;
    }

        for(let i=length-1;i>=0;i--)
        {
            console.log(arra[i]);
        }
    }
array([1,2,3,4,5,6,7,78,99]);

(Q) Write a program of given number is palindrome or not?
function Palin(n){
var temp = n;
var r;
var i=0;
while (n != 0)
{
    r =Math.round(n % 10);
    i = (i * 10) + r;
    n = Math.round(n / 10);
}
if (temp == i)
{
    console.log("It is palindrome");
else{
 console.log("It is not palindrome");
}
}
Palin(123);

(Q) Write a program of given string is palindrome or not?
function Palindrome(str)
    var temp=str;
    var revStr = "";
    var a = temp.length;
    for(i=a-1; i>=0; i--)
    {
       revStr +=temp[i];
    }
    if(str == revStr) {
       console.log(str+" -is Palindrome");
    } else {
       console.log(str+" -is not a Palindrome");
    }
    console.log(a);
 }
Palindrome("MadaM");

(Q) Write a program to find big number in the given array?
var a=[1,2,5,12,7,9,10]
var big=a[0];
for(var i=0;i<a.length;i++)
{
    if(big<a[i])
    {
        big=a[i];
    }
}
console.log(big);

/*
for(let i of a)
{
    if(big<i)
    {
        big=i;
    }
}
*/

(Q) Write a program to find out small number in the given array?
var a=[1,2,5,12,7,9,10]
var big=a[0];
for(let i of a)
{
    if(big>i)
    {
        big=i;
    }
}
console.log(big);

(Q) Write a program to print the given number is prime or not?
var a=23;
var c=0;
for(let i=0;i<=a; i++)
{
    if(a%i==0)   
    {
       c++;
    }
}
if(c==2){
    console.log("It is Prime Number");
}
else
{
    console.log("It is Not Prime Number");
}

(Q) Write a program to print first 10 prime numbers?
function prime(a){
let i=2;
let c=1;
while(c<=a)
{
var count=0;
for ( j = 2 ; j <i ; j++ )
 {
       if ( (i % j) == 0 )
        {
          count=count+1;
       }     
   }
   if (count==0 ) {
       console.log(i);
       c++;
   }           
   i++;
}           
}
prime(10);
  
(Q) Write a program to find number of words in a given statement?
var statement="Yes! this a statement";
//var words=statement.split('');
//output:- (21) 
//["Y", "e", "s", "!", " ", "t", "h", "i", "s", " ", "a", " ", "s", "t", "a", "t", "e", "m", "e", "n", "t"]
var words=statement.split(" ");
var count=0;
for(let i of statement)
{
//if(i!=(“”))
    if(i.length!==0)
    {
        count++;
    }
}
console.log(words)

(Q) Write a program to find number of characters in a given string?
var statement="Yes! this a statement";
var words=statement.split('');
var count=0;
for(let i of statement)
{
    if(i.length!==0)
    {
        count++;
    }
}
console.log(words)
console.log(count)

(Q) Write a program to print sum of all elements in given array?
var arr1=[1,2,3,4,5];
var sum=0;
for(let i=0;i<arr1.length;i++)
//for(let i=0;i<=arr1.length-1;i++)
{
    sum=sum+arr1[i];
}
console.log(sum)

(Q) Write a program to print multiplication of all elements in given array?
var a=[1,2,3,4,5,6];
var Mul=1;
for(i=0;i<a.length;i++)
{
    Mul=Mul*a[i];
    console.log(a[i]);
}
console.log("Multiplication of an array is:"+Mul)

(Q) Write a program to find second biggest number in an array?
var a=[1,2,5,12,7,9,10,13]
var firstbig=a[0];
var secondbig=a[0];
for(i=0;i<a.length;i++)
{
    if(firstbig<a[i])
    {
        secondbig=firstbig;
        firstbig=a[i];
    }
    else if(a[i]>secondbig && a[i]!=firstbig)
    secondbig = a[i];
   
}
console.log("second biggest number in an array is:"+secondbig);

(Q) Write a program to find average student object?
var student={
    Name: "Anil",
    Age:28,
    Average:function()
    {
      
        Marks=[25,24,23];
        var sum=0;
        var avg=0;
        for(var i=0;i<Marks.length;i++)
        {
            sum=sum+Marks[i];
            console.log("Total sum of marks is:"+sum);
        }
        if(sum!=0)
        {
            avg=sum/3;
        }
        console.log("Total avg of marks is:"+avg);
        return this.Name+"" +this.Age;
    }
}
console.log(student.Average())

No comments: