JavaScript by SimpliLearn 11:32:26

 JavaScript by SimpliLearn 11:32:26 hours course


1. Javascript Developed in 1995 by Brendan Eich in just 10 days.

2. Hybrid Application:
Which work any plateform like android/iOS without any problem.

3. Features of JavaScript:
 
i. JS is not a proper programming language, it is a scripting language. Which works in the runtime environment just like python.
in javascript you don't need compiler.
 

ii. JS is light-weight: In js you don't need to specify any data type or return type, which making development more quicker and that's why JS is light-weight.
 

iii. JavaScript is both client side and server side technology: Client side technology runs on the user computer and server side technology runs on the web browser. 
    initially when JS was introduced it was introduced as a client side technology.

but introduction of nodeJS in 2009, and now it use backend as well.


iv. User Validation: There is a way to validate the user data before sending it to the web server.
and we can do that with help of JavaScript. 
 
 
v. Platform Independent language : JavaScript is platform independent. Although it originally designed for work on browser only but now it is a platform independent language which mean once you done with script, you can use it on any browser and any platform without any problem.
 
 
vi.  JS is Object Oriented base Scripting Language: Many programmers do not considered, 
JS as a true Object Oriented programming language. Due to lake of class concepts.
It does support other features of Object Oriented programming like it support Encapsulation/Poly Morphism and also it support prototype inheritance.
 
vi.  JS is Case Sensitive :  But last and not the list of features, JavaScript is Case Sensitive. When it;s come to the keyboard,/identifier/Name/Function. JS differentiate between Capital and Lower case letters. We have to keep this in mind while programming on JS.








4. Applications of JavaScript 

 Where JavaScript is currently implemented.

i. web Development: It is also  main motive behind Developing JavaScript.
web technology like Angular JS/ NodeJS.
 
ii. JS is also use with HTML and CSS to  make static looking web pages more engaging.
 
iii. Mobile Application: Took the example before how Hybrid Applications made with the help of Java Script can take over traditional Android and iOS apps.

iv. One of the most important and unique application of Java Script is Smart watches.
Bengal.JS is an Open Source smart watch powered by java script.

v. Client side Validation
 
vi. Game Development: Java Script can be use to make fully flashed 2d and 3d games using different 
libraries.
Although most java script  game development focuses on creating games browser only.








5. Prerequisites for Java Script

 
i. HTML/CSS : Basic knowledge of HTML and CSS. 
To use JS along with html and css. 
you first need to know how html and css works.

HTML/CSSHtml is use to create the structured of the web pages and CSS is use by style the web pages.


ii. Java Script enabled browser.
 
iii. Need an Operating like Linux/MacOs/Windows
 
iv. Computer with minimum 500gb and 4gb of Ram.
 
 v. Need a text editor like VS Code/ Sublime/ Notepad ++
 
 
 
 

6. Facts about Java Script

 i. The only programming language that can be understood by a web browser.

ii. The popularity of java script increased from 57% in 2013 to 70% in 2017.

iii. in 2018 over 95% of the internet was powered by Javascript.



7. Reasons to use Java Script

 i. Java script is powerful frameworks
ii. constant Growth
iii. well paid
iv. beginner Friendly
v. largest Community
vi. wide Range of uses




8. DOM (Document Object Model)

i. DOM stands for Document Object Model
 
ii.  DOM is an API for HTML /XML documents.
 
iii. It is a way to define the webpages in a hierarchical way to become easy to use and manipulate.
 
iv.  It represents the entire document as Nodes and Objects.
 
 




EXAMPLE OF DOM
 
 
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
       
    </body>
    </html>
 






9. IDE
 
IDE stands for integrated Development Environment.

It is a software application basically.
It comprehensive facility to programmer for software development.
IDE make easy programmer  for write code.
Just like photoshop for photo editing.

There are numbers of IDE available on internet like VS Code/ Pycharm/ Notepad++/Sublime/comodo and so on.





VS Code is Crossed Platform mean it is available for linux/ MacOS/Windows.
 
 
 
 
 
 

10. How to embed Javascript with HTML.

How to add another folder JavaScript file in HTML file.
 
Here under script file    src = "jsFileName.js'' 
This is the way to add JS file under HTML file.
 
 
    <script src="script.js" type="text/JavaScript">
 
 
 
 
 
11.  Console.log is a function of JavaScript that work same as document.write.
 
 
12. You have to keep in mind that while giving a variable name that is you only use $ (Doller) and _ (underscore) sign only.
 
you can't use number in the beginning of any variable. 
Javascript is case sensitive.

 


13. By default if you assign any value but not declare then it will give Undefined error.
Example below:

 

    var bikeName;
    document.write(bikeName);
 
    output:  undefined
 
 
 


14. let is also used to declare a variable just like var used.

 
But there is a limitation to use Let. 
Let  is not accessible outside the block in which it is declared 
 
suppose we put this code inside a block.

    {
    let bikeName;

    bikeName = " BMW";
    document.write(bikeName);
    }
 
    document.write(bikeName)


 
and we access this variable again outside the block. 

Basically you cant access let variable outside the block scope.




 
 
 
 
But if you use var then it will not show this error.
 

    {
    var bikeName;
    bikeName = " BMW";

    document.write(bikeName);
    }

    document.write(bikeName)





See the below  it's not showing any error



Let variable used for limited only.
 
let not allowed to redeclare any declared variable. Let see an example.
 
 
 
 
 

15. const:

we use const that value we dont want to change and will never changed.
 

    const x = 5, y = 9;
    const z = x + y;
    document.write(z);

    x = x + 10;
    document.write(x)
 
 
 

also const not allow you to redeclare any variable.


16.  Data type Javascript:

Javascript Data type divideD in two category only.
 
i. Primitive Datatype : 
Primitive datatype are store in stack.
Primitive datatype are Base data type.

Primitive datatype are divided into five category.
 
Number
String
Boolean
Undefined
Null 


 
    var p = null;
    document.write(typeof(p));
  object
 

 
Undefined mean lake of value.
Null mean the absense of any value.
 suppose we use null  as the value of any variable, and the type of operator willl return it's value as an Object.
But if you are not giving any value to this variable, you are leaving it after declaration then the type of opreator will return it undefined.
 
 
    var p;
    document.write(typeof(p));
 
    output: undefined



ii. Non Primitive Datatype: 
Non Primitive datatype  are store in Heap.
Non Primitive datatype are object.
 
 
Non Primitive datatype are divided into two category.
Array and
Object
 

17. Operators in JavaScript

 i. Arithmetic Operator

Addition +
substraction -
Multiplication *
Division /
Modulus %
Increment ++
Decrement --
 

    var z = 5;
    document.write("increment operator", ++z);
    document.write("decrementoperator", --z);
 
    output: increment operator 6 decrement operator 5
 
     
 
 
 
 

ii. Assignment Operator (=)

 
    var a1 = 51;
    a1 += 9;    // increment value of a1 with 9
    a1 = a1 + 9;     // increment value of a1 with 9
    document.write(" value of a1 ", a1);

    a1 -= 5;        // decrement value of a1 with 5        
    a1 = a1 - 5;    // decrement value of a1 with 5
    document.write(" value of a1 is ", a1);
 

    a1 /= 5;        // divide value of a1 with 5        
    a1 = a1 / 5;    // divide value of a1 with 5
    document.write(" value of a1 is ", a1);
 
    a1 *= 5;        // multiply value of a1 with 5        
    a1 = a1 * 5;    // multiply value of a1 with 5
    document.write(" value of a1 is ", a1);
 
 
    a1 %= 5;        // mod value of a1 with 5        
    a1 = a1 % 5;    // mod value of a1 with 5
    document.write(" value of a1 is ", a1);


 

iii. String Operator

 
    var str = "Hello ";
    var str2 = "Javascript";
    document.write(str + str2);
   // create space by " "
    document.write(str + " " + str2);
 
 
    output: Hello Javascript  

 

 
    var str3 = "Thanks Planet";
    str3 += " for giving a chance"
    document.write(str3);

    OUTPUT: Thanks Planet for giving a chance

 


    var a = 12;
    var b = 8;
    var c = 5;

    var result = "Hello"+ a+b+c;
    document.write("<h1> value of result is \n" + result+ "\n Hie there!</h1>");

    output:

value of result is Hello1285 Hie there!

 

 

 

 
    var a = 12;
    var b = 8;
    var c = 5;

    var result = a+b+"Hello"+c;
    document.write("<h1> value of result is \n" + result+ "\n Hie there!</h1>");

      output:    

    value of result is 20Hello5 Hie there!

 

 

 


    var a = 12;
    var b = 8;
    var c = 5;
    var d = 10;
    var result = a+b+" Hello "+c+d;
    document.write("<h1> value of result is \n" + result+ "\n Hie there!</h1>");
 
    OUTPUT: 

    value of result is 20 Hello 510 Hie there!

 
 


 

iv. Conditional Operator:

 Conditional operator assign value to a variable. Based to on a certain condition.



    var x = 60;
    var y = (x >= 50) ? "true": "false";
    document.write(y);
 
    output:  true






    var x = 30;
    var y = (x >= 50) ? "true": " false ";
    document.write(y);
 
        output:  false 



 


    var x = 60;
    var y = document.write("value of x is \n", x >= 50)? "true": "false";

    output:  value of x is true

 

 

v. Logical Operator:

Logical operator are used to determine logic between  two variables or values we can say.
We use logical operator to check wether multiple condition true or false.

There are three different types of logical operator.

a. && and ( and operator if all condition true then it's gives true otherwise it's false)
b. || or operator ( or operator if any one condition true then it's gives true otherwise it's false)
c. ! not operator ( not operator if  condition true then it's gives false otherwise it's false)
 
 
let x = 7 and y = 4
 
&& => (x < 10 && y > 1)  is true
|| => (x == 5 || y == 5) is false
! => !(x==y) is true 


 


vi. Bitwise Operator:

 Bitwise operator not use daily basis.

In binary format bitwise operator works on 32 bit number.
Computer works on binary number.
 
 Here we see 4 different bitwise Operator.  and/ or/ not/ xor
 
 

 

 

    var x = 5;
    var y = 1;

    document.write(x&y);
 
    ouput: 1
 

 

 

   
     var x = 5;
     var y = 1;
    
    document.write(x|y);
 
     ouput: 5
 


 

 
    var x = 5;
    var y = 1;
    
    document.write(~x);
 
     ouput: -6




        var x = 5;
        var y = 1;
 
    
    document.write(x^y);
 
    ouput: 4
 
 
 

 

vii. Comparism Operator

 Comprism operator are similar to Logical operator in someway. There are also check for true or false.
As the name suggest we use coparism operator to compare two values. Or we can say compare two variable using different operator.


Here we see there are different types of comparism operator in JavaScript.
 
If you compare two values in Javascript then you have to use Double equal to (= =) 
Because single equal to (=)  use to assign a value.



    var x = 10;
    document.write(x == 8);
    // false
    document.write("<br>")      // use br tag for break the line.

    document.write( x === 8);
    // false

    document.write("<br>");     // use br tag for break the line.

    document.write(x != 8);
    // true

    document.write("<br>");     // use br tag for break the line.

    document.write(x !== 8);
    // true

    document.write("<br>");     // use br tag for break the line.

    document.write(x > 8 );
    // true

    document.write("<br>");     // use br tag for break the line.

    document.write(x < 9);
    // false

    document.write("<br>");     // use br tag for break the line.

    document.write(x >= 8);
    // true

    document.write("<br>");     // use br tag for break the line.


    document.write(x <= 8);
    // false


 

 

 

 

 

viii. Typeof Operator:

 Type of Operator used to provide you with type of what ever value to put right of it.
Like if you are using any datatype and want to know the data type of a particular variable then we use typeof operator.
Let say an example:

 


    var x = 10;
    var y = "London";
    var z = true;
    var p; 
 
    var abc = null;
 

    document.write(typeof (x));
    document.write(typeof (y));
    document.write(typeof (z));
    document.write(typeof (p));
 
    document.write(typeof (abc));
 
 
    output:
   
    number
    string
    boolean 
    undefined
 
    object 
 
 





18. JavaScript Statement:

Javascript statement are the instructions that tells the browser to perform specific action.
 
Cntrol statements are also instructions, they govern the flow of a program.
 
So let take a control  statement with the help of example.

let suppose we  have peace of code thats n number of statement.


in javascript we have 2 types of control statement.
 
i. Conditional statement.
we use conditional statement when we have to a made decision based on condition.
when we have 2 choices and 2 different condition. and we make choice accordingly.
and thats why we use conditional statement.
 
 Different types of Conditional statement.
if-else/ switch
 


 
ii. iterative statement or we can say looping control system.
if we want to perform any action more than one  and maybe  n number of times.
instead of writing them again and again. we  use loop.
 
we use loop to perform any activity n numbers of time with specific  condition.
 
in javascript we have 4 different types of Loop. 
i. for loop
ii. while loop
iii. do while loop
 
iv. for in loop: we use for in loop with object.



 

19. Break and Continue Statement: 

 They are not type of control statement but they do Assistent other control statement.
 
Break:  The break is used to exit a switch statement or Loop. 
Like when we use a loop we  break the loop and continue executing the code after it.
 
Continue: Continue statement break a single iteration. when we use continue statement in a loop.
it's break a single iteration and it break the iteration only if the specific condition accurred. 
And then it continue the next iteration of the loop.

 


  Let's create a basic program with a single condition

 

 
    var x = 8;
    if(x<10){
        document.write("The value of x is less than 10");
    }
    else{
        document.write("The value of x is greater than 10");
    }
 
    output:   The value of x is less than 10

 

 
    var x = 15;
    if(x<10){
        document.write("The value of x is less than 10");
    }
    else{
        document.write("The value of x is greater than 10");
    }
 
    output:
The value of x is greater than 10      

 

 
    var x = 10;
    if(x<10){
        document.write("The value of x is less than 10");
    }
    else if(x==10){
        document.write("The value of x is equals to 10")
    }
    else{
        document.write("The value of x is greater than 10");
    };
 
    output: The value of x is equals to 10  
 
 




 
    var x = 4;
    if(x %2 ==0){
        document.write("This is even number");
    }
    else{
        document.write("This is Odd number.");
    }
 
    output: This is even number




Check given number is Zero or Positive or Negative



    var y = -5;
    if(y>0){
        document.write("This is Positive number.");
    }
    else if(y<0){
        document.write("This is Negative Number.");
    }
    else{
        document.write("This is a Zero.");
    }
 
    output: This is Negative Number.
 





Check given number Positive or Negative and Even or odd and Zero.


    var x = -7;
    if(x > 0)
    {
        if(x % 2 == 0)      // nested if else
        {
            document.write("Positive and Even number.");
        }
        else    // nested if else
        {
            document.write("Positive and Odd number.");
        }
    }

    else if(x < 0)
    {
        if(x % 2 == 0)       // nested if else
        {
            document.write("Negative and Even number.");
        }
        else            // nested if else
        {
            document.write("Negative and Odd number.");
        }
    }

    else
    {
        document.write("Number is zero.");
    }
 
    output:  
    Negative and Odd number.



 
    var x = 8;
    if(x > 0)
    {
        if(x % 2 == 0)      // nested if else
        {
            document.write("Positive and Even number.");
        }
        else    // nested if else
        {
            document.write("Positive and Odd number.");
        }
    }

    else if(x < 0)
    {
        if(x % 2 == 0)       // nested if else
        {
            document.write("Negative and Even number.");
        }
        else            // nested if else
        {
            document.write("Negative and Odd number.");
        }
    }

    else
    {
        document.write("Number is zero.");
    }

    output:      
Positive and Even number.


Another way to print this solution



    // another way

    var x = 7;
    if(x>0 && x % 2===0)
    {
        document.write("Number is positive and Even");
    }
    else if(x>0 && x % 2 !==0)
    {
        document.write("Number is Positive and Odd");
    }
    else if(x < 0 && x % 2 ===0)
    {
        document.write("Number is Negative and even");
    }
    else if(x < 0 && x%2 !==0)
    {
        document.write("Number is Negative and Odd");
    }

    else
    {
        document.write("Number is Zero.");
    }
 
    output: Number is Positive and Odd  





Write a program by month in a year by accepting number.

for example if we enter 4 then output will be april.
 
 
    var x = 5;
    if(x ===1)
    {
        document.write("January");
    }
    else if(x === 2)
    {
        document.write("February");
    }
    else if(x === 3)
    {
        document.write("March");
    }
    else if(x === 4){
        document.write("April");
    }
    else if(x === 5)
    {
        document.write("May");
    }
    else if(x===6)
    {
        document.write("June");
    }
    else if(x === 7)
    {
        document.write("July");
    }
    else if(x ===8)
    {
        document.write("August");
    }
    else if(x === 9)
    {
        document.write("September");
    }
    else if( x === 10)
    {
        document.write("October");
    }
    else if(x === 11)
    {
        document.write("November")
    }
    else if(x === 12)
    {
        document.write("December");
    }

    else
    {
        document.write("Wrong input");
    }
    
    output: May

 

 Another way using Switch case


    //  Using Swith case

    var month = 6;
    switch(month)
    {
        case 1:
            document.write("January");
            break;
        case 2:
            document.write("February");
            break;
        case 3:
            document.write("March");
            break;
        case 4:
            document.write("April");
            break;
        case 5:
            document.write("May");
            break;
        case 6:
            document.write("June");
            break;
        case 7:
            document.write("July");
            break;
        case 8:
            document.write("August");
            break;
        case 9:
            document.write("September");
            break;
        case 10:
            document.write("October");
            break;
        case 11:
            document.write("November");
            break;
        case 12:
            document.write("December");
            break;
        default:
            document.write("You entered invalid key.")
    };
      
    output: June  
     
 



20. Switch Case:

Now let's talk about Switch Case. 
Switch case accept Number Boolean and String as well as.
 
 
    //  swith case

    var month = "12";

    switch(month)
    {
        case "June":
            document.write("Six Month");
            break;
        case "January":
            document.write("Month One");
            break;
        case "February":
            document.write("Month Two");
            break;
        case "March":
            document.write("Month Three");
            break;
        case "April":
            document.write("Months Four");
            break;
        case "May":
            document.write("Month Five");
            break;
        case "July":
            document.write("Months Seven");
            break;
        case "August":
            document.write("Month Eight");
            break;
        case "September":
            document.write("Nine");
            break;
        case "October":
            document.write("Months Ten");
            break;
        case "November":
            document.write("Months Eleven");
            break;
        case "December":
            document.write("Months Twelve");
            break;
        default:
            document.write("This is wrong.");

    }
 
    output: December
 
 








    var month = false;

    switch(month)
    {
        case true:
            document.write(1);
            break;
        case false:
            document.write(0);
            break;
        default:
            document.write("invalid input.")
    }
 
    output: 0 
 







 
    var month = true;

    switch(month)
    {
        case true:
            document.write(1);
            break;
        case false:
            document.write(0);
            break;
        default:
            document.write("invalid input.")
    }
 
 
     output: 1
 









21. Function:  

 Function stats that  to work on a proper and particular way.
Similarly function in javascript are block of code that is used to perform a specific task.

Let's understand syntax and uses of function.

Function has a particular name  and we can resue that block of code again and again in a entire program.

 

Basically function have 3 parts.

a.  Function Declaration
b. Function Definition.
c. Function Calling.


 

 
    var x = 10,
    y = 5,
    tatal = x + y;

   document.write(tatal);
 
    output: 15 
 
 

 

let write above program under a function. 

This is the basic how to write a function and how function work.


    function sum()
    {
        var x = 10,
        y = 5,
        tatal = x + y;

    document.write(tatal);
    }
    sum();
    
    output: 15 


 

Function also have Parameter. See below

 
    function sum(x,y)
    {
    var tatal = x + y;

    document.write(tatal);
    }
    sum(5,10);
 
     output: 15 


 

We can also pass string under function parameter.

 
    function sum(x, y)
    {
        let num = x + y;
        document.write(num);
    }
    sum("passing string under function parameter ", "welcome JS");


    output: passing string under function parameter welcome JS

 

 

Return in function

 

 
    function sum(x, y)
    {
        let num = x + y;
        return num;
    }
    let total = sum(33,44);
    document.write(total);
     
    output: 77 
 









22. Scope of variable in JavaScript

what does Scope mean in variable scope refer to the life of a variable in a program.
There are basically 2 types of variable present in java script.
 
i. Local variable
when we declare a variable inside a function and that is a Local variable.
 
See Local variable example.
 

    function myFun()
    {
        let x = 20;
        document.write(x);
    }

    myFun()
 
 
    OUTPUT: 20 
 
 
 
 It is not possible to access local variable outside the function.
See below example. 


    function myFun()
    {
        let x = 20;
   
    }

    myFun();
    document.write(x);
 
    output: no output
 
 
 

ii. Global Variable.
See Global variable example.
 

    // Here a is a Global variable

    var a = 55;
    document.write("<h1>" + a + "</h1>");
    document.write(a);

    document.write("<h1>" + a + "</h1>");
     
    output:

    55

        55

    55

 

 
 But we can access Globall variable inside the function.
Let see


    var y = 40;
    function myFun()
    {
        let x = 20;
        document.write(x);
        document.write(y);
    }

    myFun();
 
    output: 20 40  



var is a keybord that work without  declare var ketboard.
Let see

 
    function myFun()
    {
        var1 = 5999; // var is a keybord that work without  declare var ketboard.
        let x = 20;
        document.write(x);
    }

    myFun();
    document.write("<br>");
    document.write(var1);

    output:     20
    5999
    


Remember: Any variable without using var keyboard is a Globall variable.
 
 
 
 

23. String:

Strings are any program language are used to store and manipulate Textual value.

String are helpful for holding data that can be representating Textual form.

Strings contain sequece of character retun inside double and single code. (" ", ' ')

lets declare a basic string.

 
    var x = "This is a String";
    document.write(x, "<br>");
    document.write(typeof (x));
 
     Output:    
     This is a String
     string
 

 

24. Escape sequence in JavaScript.

Here we use HTML tag inside the javascript. (br tag)

   
     document.write("Hi there. <br> Welcome to my JavaScript.")
 
      Output:         Hi there.
       Welcome to my JavaScript.  
 


Double quote

 
    document.write("Hi there. \"This\" Welcome to my JavaScript.")
 
    output:  Hi there. "This" Welcome to my JavaScript.
 

Single quote

 
    document.write("Hi there. \'This\' Welcome to my JavaScript.");
    output: Hi there. 'This' Welcome to my JavaScript.
 


\ =====> Back slash


     
    document.write("It\'s Alright");
 
    output:   It's Alright




 
    document.write("The character \\ is called backslash.");
    output: The character \ is called backslash.
 




25. Array:

 
    var car = ["Honda", "Kia", "Ford"];
    document.write(car);
 
    output:  Honda,Kia,Ford




Print second element Kia only.

 
    var car = ["Honda", "Kia", "Ford"];
    // document.write(car);
    document.write(car[1]);
 
    output: Kia
 



Run above Array using for loop.

 
    var car = ["Honda ", "Kia ", "Ford"];

    for(var i = 0; i < car.length; i++)
    {
        document.write(car[i]);
    }

    output: Honda Kia Ford



Print array using for loop and Header 1 
 
 
 
    var fruits = ["Apple", "Banana", "Blackberry", "Graps","Plam"];

    for(var i =0; i < fruits.length; i++);
    {
        document.write(`<h1> ${fruits[i]} </h1>`);
        // document.write("<h1>" + fruits[i] + "</h1>");   
    }
 
    output: 

    Apple

    Banana

    Blackberry

    Graps

    Plam

         



Push:

Add new element to the array using push keyboard.


    var fruits = ["Apple", "Banana", "Blackberry", "Graps","Plam"];

    fruits.push("Orange");

    for(var i =0; i < fruits.length; i++)
    {
        document.write(`<h3> ${fruits[i]} </h3>`);
        // document.write("<h3>" + fruits[i] + "</h3>");
    }
 
     output:

    Apple

    Banana

    Blackberry

    Graps

    Plam

    Orange





Pop:

 Pop method in array remove the last element from the array.

See last element  Palm Removed from the array.


    var fruits = ["Apple", "Banana", "Blackberry", "Graps","Plam"];

    fruits.pop();

    for(var i =0; i < fruits.length; i++)
    {
        document.write(`<h3> ${fruits[i]} </h3>`);
        // document.write("<h3>" + fruits[i] + "</h3>");
    }


    output:

    Apple

    Banana

     Blackberry

     Graps




push a numeric value

    var fruits = ["Apple", "Banana", "Blackberry", "Graps","Plam"];

    fruits.push(666);

    for(var i =0; i < fruits.length; i++)
    {
        document.write(`<h4> ${fruits[i]} </h4>`);
        // document.write("<h4>" + fruits[i] + "</h4>");
    }
    

    OUTPUT:

    Apple

     Banana

     Blackberry

    Graps

    Plam

     666





26. Object:

Object are the most powerful  and most used datatype in JavaScript.



 
    var car_manufacture = "Audi";
    var car_model = "Q7";
    var price = 50000;

    function allWheeldrive()
    {
        document.write("This car comes with Quattro all-wheel drive.");
    }
    allWheeldrive();
 
    output: This car comes with Quattro all-wheel drive.  

 

When ever we used function  inside a class or an object so it is known as a method.
Keep in mind this.
 
Syntax is also bit different when it comes to method inside an object.
 
 
 
 
 Lets see object demo
 
 
    var car =       // car is an object name.
    {
        car_manufacturer : "Audi",      // car_manufacture property name of car object
        car_model : "Q7",               // car_model property name of car object
        price : 5000,                   //price  property name of car object

        allwheeldrive : function()      // this is syntax or Method for object
        {
        return("This car comes with Quattro all-wheel drive.");
        }
    }
    document.write(car.car_manufacturer);   // access all property by object name car and dot(.) and property name
    document.write(car.allwheeldrive()); 
 
 
    output:   AudiThis car comes with Quattro all-wheel drive.
 
 
 
 

 See and understand hoe object works

 
 
  var car =       // car is an object name. 
 
{
        car_manufacturer : "Audi",      // car_manufacture property name of car object
        car_model : "Q7",               // car_model property name of car object
        price : 5000,                   //price  property name of car object
 
        allwheeldrive : function()      // this is syntax or Method for object
        {
        return("This car comes with Quattro all-wheel drive.");
        }
    }
    document.write(car.car_manufacturer);   // access all property by object name car and dot(.) and property name
    document.write(car.allwheeldrive());  // access the method by object name and dot(.) and methhod name and parenthesis()
 
 
 
 
 
 
 

Constractor function

Now we create multiple object using a single Templates. Which is known as Constractor function.

 Inside the body we will use "this"  Keyboard

This keyboard refer to the object it belong. So here to the program this will refer to the object only.


 


    // This is a complete Constractor function. This Constractor function work like template.

    function cars(car_manufacture, car_model, price// this are propertise of Object (car_manufacture, car_model, price)
    {
        this.car_manufacture = car_manufacture; //  actual property of the object will be this.car_manufacture
        this.car_model= car_model;
        this.price = price;

        this.allWheeldrive = function()     // this is function or method
        {
            document.write("This car comes with four wheel drive.");
        }
    }

    var c1 = new cars("Audi", "Q7", 50000);
    c1.allWheeldrive();         // this c1 access allWheeldrive
 
    output:   This car comes with four wheel drive.


 
 
 

 And this is how we can create multiple object in javascript

 

 
    // This is a complete Constractor function. This Constractor function work like template.

    function cars(car_manufacture, car_model, price) // these are propertise of Object (car_manufacture, car_model, price)
    {
        this.car_manufacture = car_manufacture//  actual property of the object will be this.car_manufacture
        this.car_model= car_model;
        this.price = price;

        this.allWheeldrive = function()     // this is function or method
        {
            document.write("This car comes with four wheel drive.");
        }
    }

    var c1 = new cars("Audi", "Q7", 50000);
    c1.allWheeldrive();         // this variable c1 access allWheeldrive

    var c2 = new cars("BMW", "X7",40000);
    document.write("<br>")    // this is br tag
    c2.allWheeldrive();
    document.write("<br>")    // this is br tag
    document.write(c1.car_manufacture);  // access  car_manufacture
    document.write("<br>")    // this is br tag
    document.write(c2.price); // access c2 price
 
 
  output:     This car comes with four wheel drive.
    This car comes with four wheel drive.
    Audi
    40000      
 
 
 

 Literal Object:

 Literal obeject is bit easier than other one which is constractor function.

 

 Here we created car object, which has 3 propertise car_manufacurer/ car_model/ Price and 

we have a method here as "allWheeldrive".

and we use this  method with help of dot (.) operator. we call that method with the help of object.

 
 
    var car_manufacture = "Audi";
    var car_model = "Q7";
    var price = 50000;

    function allWheeldrive()
    {
        document.write("This car comes with Quattro all-wheel drive.");
    }
    allWheeldrive();




 

 
Object in javascript , lot of things we know about Javascript are basically Object.
Like Boolean value/ Number/ Strings and few more and many of this thing can be object if we define them with new keyboard. Basically any of the data type other than the Null and undefined can be convert to Object.

We have few pre defined object as well. We have the Math Object/ Date Object / Regular Express are also considered as an object in javascript.

string is a datatype and we also use string as an Object like below.
 
This is a basic datatype that how to define primitive datatype into an Object.
 
   
 
    var str1 = new String()
 



String Object



    var str1 = new String("This is a string Object.");
    document.write(typeof (str1) + "<br>");  // Here we used br tag for next line
    // document.write("<br>");     // this is br tag for next line

    document.write(str1);
      
    output: object
            This is a string Object.  
 



Adding car_color property to the existing object.


    var car =
    {
    car_manufacture : "Audi",
    car_model : "Q7",
    price : 50000,

    allWheeldrive :function ()

    {
        document.write("This car comes with Quattro all-wheel drive.");
    }

    }

    car.allWheeldrive();
    // adding car_color propertice to the object
    car.car_color = "Black";

    document.write(car.car_color);
      
    output:      This car comes with Quattro all-wheel drive.Black





Adding new method or function to the existing  object.

 

 
   // adding new method or function to the existing object
    car.newfun = function()
    {
        return("Function successfully added.");
    }

    document.write(car.newfun());
    // document.write("<br>"+ car.newfun()); // br tag for next line




 

How to delete method or function and property from existing Object.

 

 
    // delete a property from the existing Object
    delete car.car_color;
    document.write(car.car_color);
 
    output: undefined  because car color was deleted. 


 

 

How to update property from existing Object.

 
    var car =
    {
    car_manufacture : "Audi",
    car_model : "Q7",
    price : 50000,

    allWheeldrive :function ()

    {
        document.write("This car comes with Quattro all-wheel drive.");
    }

    }

    car.allWheeldrive();
 
    // How to update property from existing Object.

    car.price = "9000000";
    document.write(car.price);
 
    output: This car comes with Quattro all-wheel drive.9000000 




How to check the datatype of Operator are used  in Object

 
    var car =
    {
    car_manufacture : "Audi",
    car_model : "Q7",
    price : 50000,

    allWheeldrive :function ()

    {
        document.write("This car comes with Quattro all-wheel drive.");
    }

    }

    // How to check what type of operator are used to an existing Object.Lets check
    document.write(typeof (car.price));
 
    output: number







In javaScript we can use Constractor in 2 different ways.
 
i.  Object Constractor Method
ii.  Constractor Function.


i.  Object Constractor Method

This is the syntax of creating an empty Object by using the Object Constractor method.

 
    var object_name = new Object();
 

It will remain the same every time we use the Object Constractor Method.





 
   var rect2 = new Object();   // or  var rect1 = {};
    rect2.length = 5;   // add property to an Object
    rect2.width = 10;   // add property to an Object

    // Let's add method to this object. Here we add 2 method
    rect2.getarea = function()  // This is method 1
    {
        return this.length*this.width;
    }

    rect2.getperameter = function()     // This is method 2
    {
        return 2*this.length + 2*this.width;
    }

    document.write("<h2>"+ "The length of rectangle is "+ rect2.length + "</h2>");
    document.write("<h2>"+ "The width of rectangle is " + rect2.width + "</h2>");
    document.write("<h2>"+ "The area of rectangle is " + rect2.getarea() + "</h2>");
    document.write("<h2>"+ "The perimeter of rectangle is " + rect2.getperameter() + "</h2>");
 
    or

    // document.write(rect2.length);
    // document.write(rect2.width);
    // document.write(rect2.getarea());
    // document.write(rect2.getperameter());

    output:    

    The length of rectangle is 5

    The width of rectangle is 10

    The area of rectangle is 50

    The perimeter of rectangle is 30

 





another way to print above program

 
    function rect3(length,width)
    {
        this.length =length;
        this.width = width;
       
        this.getarea = function()
        {
            return length * width;
        }

        this.getperameter = function()
        {
            return 2 * length + 2 * width;

        }
    }

    var r1 = new rect3(5,10);
    document.write("<h2>"+r1.length +"<h2>");
    document.write("<h2>"+r1.width +"<h2>");
    document.write("<h2>"+ "The area of rectangle is "+ r1.getarea());
    document.write("<h2>"+ "The perameter of rectangle is "+ r1.getperameter());
 
    output:

    5

    10

    The area of rectangle is 50

    The perameter of rectangle is 30















27. Object Prototype in Javascript

In simple word all javaScript Object inheritat property and method from a prototype.

Date object inherit from date Dot prototype.

Array object inherit  from array Dot prototype.

parcent object all these object inherite their propertise from object Dot prototype.



    var abc = {
        name: "Sayid",
        Subject: "Javascript",
        Address: "Turkey",
    }

    console.log(abc);
 
 





We can't make changes Object Prototype. 
It is not a good practice to edit Object Dot prototype.


 
    function xyz(name, subject, Address)
    {
        this.name = name;
        this.subject = subject;
        this.Address = Address;
    }

    xyz.prototype.getName = function(){
        return this.name;
    }

    xyz.prototype.getAddress = function()
    {
        return this.Address;
    }

    // creating an Object
    var x1 = new xyz("Kaushal", "Javascript", "Earth");
    var x2 = new xyz("Samh", "Paython", "Mars");
    console.log(x1);










28. Prototypal Inheritance in Javascript


 
Employee =
    {
        post: function()
        {
            return "A software Developer";
        },
       
        changeName : function(name)
        {
            this.name = name;
        }
    };

    // created an object below
    var e1 = Object.create(Employee);
    e1.name = "Kaushal";
    e1.role = "Writer";


    var e1 = Object.create(Employee, {
        name : {value : "Kaushal22"},
        role : {value : "Programmer"},
    })

    e1.changeName("Ram");
    console.log(e1);










 
   
    //  This is a  constructor function
    function Employee(name, id, salary)
    {
        this.name = name;
        this.id = id;
        this.salary = salary;
    }

    // This is  method
    Employee.prototype.post = function()
    {
        return (this.name +" "+ "is a content creator");
    }

    //  This is Object
    var Kaushal = new Employee("Kaushal",2323, 10000000);
    console.log(Kaushal)


    //  This is adding another constructor function for  above object
    function Programmer(name, id, salary, language)
    {
        Employee.call(this, name, id, salary);
        this.language = language;
    }
    Programmer.prototype = Object.create(Employee.prototype);
    Programmer.prototype.constructor = Programmer;
    var Arun = new Programmer("Arun", 34344, 12345666, "javascript");
    console.log(Arun);







29. Classes and inheritance in JavaScript:

Class is  nothing but  a template used for creating Object in javascript.
Just like constructor function, we can also use classes for creating Object in
Javascript.

We can include propertise and behaviour in our class. Creating a class is pretty
easy job.


To declare a Class we used Class keyboard followed by name of the class and body of
the class.


This is an empty class 
 
 
    class Student {

    };



This is the basic syntax of class, and how we are going create class in JavaScript

 
    class Student
    {
        // this is constructor
        constructor(name,age, roll)
        {
        // Adding propertise to this class
        this.name = name;
        this.age = age;
        this.roll = roll;
        }
    }









 
    class Student
    {
        // this is constructor
        constructor(name,age, roll)
        {
        // Adding propertise to this class
        this.name = name;
        this.age = age;
        this.roll = roll;
        }

    // adding method  and // this is the syntax for definig a method in classes.
        org()
        {  
            return ("I am "+ this.name + "from simplicode");
        }
        // another method for DOB
        dob()
        {
            return ("The date of birth of " + this.name + " is " + (2020-this.age));
        }
    }

    // this is Object
    var Kaushal = new Student("Kaushal", 32, 56);
    console.log(Kaushal);





 
    class Student
    {
        // this is constructor
        constructor(name,age, roll)
        {
        // Adding propertise to this class
        this.name = name;
        this.age = age;
        this.roll = roll;
        }

    // adding method  and this is the syntax for definig a method in classes.
        org()
        {  
            return ("I am "+ this.name + "from simplicode");
        }
        // another method for DOB
        dob()
        {
            return ("The date of birth of " + this.name + " is " + (2020-this.age));
        }

    // this is static method
    static add(a,b)
    {
        return (a+b);
    }
    }

    // this is Object
    var Kaushal = new Student("Kaushal", 32, 56);
 
    console.log(Kaushal);
    console.log(Student.add(10,45));







NB: extends is a keyboard, which is use for inheritance.
 
 
 

        class Student
        {
            // this is constructor
            constructor(name,age, roll)
            {
            // Adding propertise to this class
            this.name = name;
            this.age = age;
            this.roll = roll;
            }

        // adding method  and // this is the syntax for definig a method in classes.
            org()
            {  
                return ("I am "+ this.name + "from simplicode");
            }
            // another method for DOB
            dob()
            {
                return ("The date of birth of " + this.name + " is " + (2020-this.age));
            }

        // this is static method
        static add(a,b)
        {
            return (a+b);
        }
        }


        class Student1 extends Student
        {
            constructor(name, age, roll, language,section)
            {
                super(name, age, roll);
                this.language = language;
                this.section = section;
            }
        }

    var Arun = new Student1("Arun",24,2,"Javascript","A");
    console.log(Arun);
    console.log(Student1.add(65,8));


 
 
 
 
 

30. GetElementbyTagName Method  in Javascript

 

TagName Method also quite useful when we want to access element with the same Tag name. we can access all the similar tag present within HTML document with the help of Tag name.
 
 JS file
 
 
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <h1>GetElementbyTagName Method in Javascript.</h1>
        <div>This is section 1</div>
        <form>
            Name:<input type="text" name="Name"><br>
            Age: <input type="number" name="Age"><br>
        </form>

        <div>This is section 2</div>
        <input type="radio" name="Group1" value="A">A<br>
        <div>This is section 3</div>
        <input type="radio" name="Group1" value="A">B<br>
        <div>This is section 4</div>
        <br>
        <input type="button" onclick="Fun2()" value="Submit">
    </body>
    <script src="tagname.js" type= "text/Javascript">
    </script>
    </html>
 
 
 
 HTML file

 
 
    function Fun2()
    {
        var x = document.getElementsByTagName("div");
        for(var i = 0; i < x.length; i++)
        {
            // x[i].style.fontWeight = "Bolder";
            x[i].style.backgroundColor = "red";
        }



        x.style.fontFamily = "Courier New";
    //     x[1].style.color = "red";
    //     x[2].style.fontStyle = "italic";
    //     x[3].style.background = "green";
    }


 
 
 
 
 

30. GetElementByClassName() Method in Javascript.

 We can access two Different tag with same class name with help of class name method  in JavaScript.
 
 




 
 

31. id method is  used when we access a single element.

 

 

32. Callback function in javaScript:

Functions in javascript are block of code. That is used to perform a specific tasks.

we use function for different purposes, weather it be button clickor we want to zoom out or images by taking the mouse cursor over it. we use functions for all these task.

In javascript we can use function as Object.

at the same time we can pass object to function as perameter, simililarly we can also pass a function inside another function.

 

Call back function is a function that is pass to another function as an argument.

 
 
 

 
    function one(){
        setTimeout(function(){
        console.log("Function 1");
        two();  // function 2 calling here

        },3000)

    }

    function two(){
        console.log("Function 2");

    }

    function three(){
        console.log("Function 3");
    }

    // setTimeout(one, 2000); // fnction 1 will be executed after 2 sec
    // three();

    one();
    // two();



 
 
 
 
 
 Create a function and pass an argument inside this function.

 
 
    // Create a function and pass an argument inside this function.

    function person(friend, person2)
    {
        setTimeout(function(){


        console.log("My friends name is " + friend);
        person2();}, 3000);
    }

    function person2()
    {
        console.log("My name is amyy");
    }


    person("Simplicode", person2);      // person2 passing as an argument
    // person2();
 
 
 
 
 
 

32. Promises


 
    var promis = new Promise(function(resolve,reject){
       
        // var drive = true;
        var drive = false;
        if(drive)
        {
            resolve("Yes");
        }
        else
        {
            reject("No");
        }
    });


    promis.then(function(resolve){
        console.log(resolve + " the user know how to drive.")
    }).catch(function(reject){
        console.log(reject + " the user does not know how to drive.")
    })
 
    output: No the user does not know how to drive.
     




32. Arrow  Functions in Javascript

    // function func1(a, b)
    // {
    //     return a +b;
    // }

    // function func2()
    // {
    //     console.log("Welcome to JavaScript");
    // }

    // func2();


    //  Arrow function

    /* function func1(a, b)
    {
        return a +b;
    }

    var arrow1 = (a , b) =>
    {
        return a +b;
    }
    */

    function func2()
    {
        console.log("Welcome to JavaScript");
    }

    func2();


    var arrow2 =() =>
    {
        console.log("Welcome to Javascript learn.");
    }

    arrow2();

    var arrow3 = newname =>
    {
        console.log("Hey there! " + newname);
    }

    arrow3("Kaushal");






33.  Timing Functions in JavaScript

setTime method is a predefined function in javascript that does some task after an interval of time.
 
 
 
HTML file
 
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-widthdevice-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <h1>Timing Function in JavaScript</h1>
        <script src="timingFunctions.js " type="text/JavaScript">
        </script>
        <button onclick="Start()"> click Me </button>
    </body>
    </html>
 
 
 
 JS File
 
 
    var message = () => alert("Welcome to JavaScript.");

    //  setTime method
    function Start()
    {
        setTimeout(message, 2000);
    }




 
JS File
 Anonymous fuction

    //  Anonymous function
    function Start()
    {
        setTimeout(function(){      // this is anonymous function without name.
            alert("welcome back");
        },2000)
    }



 





HTML File

 
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-widthdevice-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <h1>Timing Function in JavaScript</h1>
        <script src="timingFunctions.js " type="text/JavaScript">
        </script>
        <button onclick="Start()"> Click Me </button>
        <button onclick="Stop()"> Stop </button>
    </body>
    </html>
 




JS File 
Set Time Out


    var id = 0;
    var message = () => alert("Welcome to javaScript Learning");

    function Start(){
    id = setTimeout(message, 5000);
    };

    function Stop(){
        clearTimeout(id);
    };





JS file
Set interval
 

    var id = 0;
    var message = () => alert("Welcome to javaScript Learning");

    function Start(){
    id = setInterval(message, 5000);
    };

    function Stop(){
        clearTimeout(id);
    };








34. async-await in JavaScript

 HTML file

 
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-widthdevice-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <h1>async-await in JavaScript</h1>
        <script src="async.js" type="text/JavaScript">
        </script>

    </body>
    </html>
 

 

JS file



    function makeOrder(Coffee)
    {
        return new Promise((resolve, reject)=>
        {
            console.log("Making request for a "+ Coffee)
            if(Coffee == "Black coffee")
            {
                resolve("Here is your coffee, Have a nice day")
            }
            else
            {
                reject("Sorry! We serve black coffee Only.")
            }

        })
    }

    function processOrder(order)
    {
        return new Promise((resolve, reject)=>{
            console.log("Processing order")
            resolve("Extra Information "+ order)
        })
    }

    makeOrder("Black coffee").then(order=>{
        console.log("Order has been received.")
        return processOrder(order)
    }).then(processedOrder =>{
        console.log(processedOrder)
    }).catch(error =>{
        console.log(error);
    })
 
     output:
 
    Making request for a Black coffee async.js:7:17
    Order has been received. async.js:29:13
    Processing order async.js:23:17
    Extra Information Here is your coffee, Have a nice day 
     




If user want "latte" then output will be shown as

HTML file

 
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-widthdevice-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <h1>async-await in JavaScript</h1>
        <script src="async.js" type="text/JavaScript">
        </script>

    </body>
    </html>
 

 

JS file

 
    function makeOrder(Coffee)
    {
        return new Promise((resolve, reject)=>
        {
            console.log("Making request for a "+ Coffee)
            if(Coffee == "Black coffee")
            {
                resolve("Here is you coffee, Have a nice day")
            }
            else
            {
                reject("Sorry! We serve black coffee Only.")
            }

        })
    }

    function processOrder(order)
    {
        return new Promise((resolve, reject)=>{
            console.log("Processing order")
            resolve("Extra Information "+ order)
        })
    }

    // makeOrder("Black coffee").then(order=>{
    makeOrder("Latte").then(order=>{
        console.log("Order has been received.")
        return processOrder(order)
    }).then(processedOrder =>{
        console.log(processedOrder)
    }).catch(error =>{
        console.log(error);
    })

    output:
    
    Making request for a Latte.
    Sorry! We serve black coffee Only.





    async function func1()
    {try
        {


        var order = await makeOrder("Black Coffee");
        console.log("Order has been received.");
        var processedOrder = await processOrder(order)
        console.log(processedOrder);
        }
    catch(error)
    {
        console.log(error)
    }
    }

    func1();




35. Errors

missing curly braces and other symbols that is called syntax error

Here closing curly braces missing and this is syntax error
 
    function f1()
    {
        console.log("This is function 1")


    f1();





ReferenceError 

Here we wrongly call unknown function name and this type of error are Reference error.
 
    function f2()
    {
        console.log("This is function 2")
    }

    f3();




Customise error for watch to the user.


    function makeOrder()
    {
        console.log("Here is your Black Coffee, Enjoy your day. ")
    }

    try{
        makeOrder();
        processOrder();
       
    }
    catch (error){
        console.log("Sorry, an error occurred in your program");
    }
 
     output: 
    Here is your Black Coffee, Enjoy your day.
    Sorry, an error occurred in your program 
 




throw Error:
 

    var a =9;
    if(a<10)
    {
        throw new Error("This is a customisable error.")
    }
    else
    {
        console.log("working fine.")
    }
 
 
    output: This is a customisable error. 
 



36. Regular Expression (Regex)

These character are called Meta Character 
 
 
    var regex = /Hey/
    var str1 = "welcome to javascript world. Hey there how are you.";

    // exec()

    var output = regex.exec(str1);
    console.log(output);
 
    output: 
    Array [ "Hey" ]
    0: "Hey"
    
    groups: undefined
    index: 29
    input: "welcome to javascript world. Hey there how are you."
    length: 1
    <prototype>: Array [] 
 



These character are called Meta Character


    // var regex = /Hey/i
    // var regex = /Hey/g  // globall
    var regex = /Hey/
    var str1 = "welcome to javascript world. Hey there how are you.";

    // exec()   // this  is exact function

    // var output = regex.exec(str1);
    // console.log(output);


    // test()               // this  is test function

    // var output = regex.test(str1);
    // console.log(output);



    // match()                  // this  is math function

    var output = str1.match(regex);
    console.log(output);


    // replace method

    var output = str1.replace(regex, "Hii");
    console.log(output);





       
    // var regex = /Hey/
    let regex = /W*e/;
    var str1 = "welcome to javascript world. Hey there how are you. Are you there ?";

    let output = regex.test(str1);
    console.log(output);

    let op = regex.exec(str1);
    console.log(op);
 
    output: 
    true

 






^ ---> this character only true when all character match
These character are called Meta Character 


    // var regex = /Hey/

    // ^ ---> this character only true when all character match
    let regex = /^Welcome/;
    var str1 = "Welcome to javascript world. Hey there how are you. Are you there ?";

    let output = regex.test(str1);
    console.log(output);

    let op = regex.exec(str1);
    console.log(op);
 
    output:
    true 
 
    Array [ "Welcome" ] 







    // var regex = /Hey/

    // ^ ---> this character only true when all character match
    let regex = /^Welcome/;
    var str1 = "welcome to javascript world. Hey there how are you. Are you there ?";

    let output = regex.test(str1);
    console.log(output);

    let op = regex.exec(str1);
    console.log(op);
    
    output:
    false
    null





$ ---> this character only true when last character match
These character are called Meta Character 

 


    // $ ---> this character only true when last character match
    let regex = /Welcome$/;
    var str1 = "welcome to javascript world. Hey there how are you. Are you there ?";

    let output = regex.test(str1);
    console.log(output);

    let op = regex.exec(str1);
    console.log(op);
 
    output: 
         false
         null 






    // $ ---> this character only true when last character match
    let regex = /back$/;
    var str1 = "welcome to javascript world. Hey . Are you there then back";

    let output = regex.test(str1);
    console.log(output);

    let op = regex.exec(str1);
    console.log(op);
 
    
    output: true
            Array [ "Welcome" ]
 







??  ---> this character only true when  character match left or right or anywhe
These character are called Meta Character 

    // ??  ---> this character only true when  character match left or right or anywhere exists
    let regex = /Welc?ome?/;
    var str1 = "welbome to javascript world. Hey there how are you. Are you there then Welcome";

    let output = regex.test(str1);
    console.log(output);

    let op = regex.exec(str1);
    console.log(op);
 
 
      output:
    true
    Array [ "Welcome" ] 
 

These character are called Meta Character 





37. Character sets and Ranges in RegEx.


    var regex = /[abc]def/
    var str1 = "This string constains adef";
    var output = regex.test(str1);
    console.log(output);

    output: true




    var regex = /[abc]def/
    var str1 = "This string constains rredef";
    var output = regex.test(str1);
    console.log(output);

   output: false




    var regex = /[abc]def/
    var str1 = "This string constains Kaushadef";
    var output = regex.test(str1);
    console.log(output);

    output: true





 
    //  a-z mean this character check all character between range A to Z
    var regex = /[a-z]def/
    var str1 = "This string constains Khdjfhdef";
    var output = regex.test(str1);
    console.log(output);
 
     output: true
 



 
    //  a-z mean this character check all character between range A to Z
    var regex = /[a-z]def/
    var str1 = "This string constains uytuyudef";
    var output = regex.test(str1);
    console.log(output);
 
    output: true 
 




    //  a-z mean this character check all character between range A to Z
    var regex = /[a-z]def/
    var str1 = "This string constains uytuy5def";
    var output = regex.test(str1);
    console.log(output);
 
     output: false
  




^def mean not include def character before def


    // ^def mean not include def character before
    var regex = /[^def]def/
    var str1 = "This string constains abdfdef";
    var output = regex.test(str1);
    console.log(output);

    // output: false






    // ^def mean not include def character before def
    var regex = /[^def]def/
    var str1 = "This string constains alabadef";
    var output = regex.test(str1);
    console.log(output);

    // output: true
 



 
    // ^def mean not include cow character before def
    var regex = /[^cow]def/
    var str1 = "This string constains cowdef";
    var output = regex.test(str1);
    console.log(output);

    // output: false







38. Validation in  JavaScript

Js File

 
    function employee()
    {
        var empid = document.getElementById("eid").value
        var check = /[DE]253[10-99]/i   // i mean allow lower case
        // var check = /[DE]253[10-99]/     // this is Upper case
        if((check.test(empid)))
        {
            alert("Valid employee ID.");
        }
        else
        {
            alert("Invalid employee ID.");
        }
    }


    //  id should be D253311 E25361 then it show Valid otherwise Invalid
 

 
HTML File

 
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <h1>Validation</h1>
        <form>
            <input id="eid" placeholder="Employee ID" type="text">
            <button onclick="employee()">Submit</button>
        </form>
   
        </body>
    <script src="validation.js" type= "text/Javascript">
    </script>
    </html>
 





39. Short-hand Character Class


    // var regex = /321/
    // var str1 = "User Phone number is 9876543210";

    // var output = regex.exec(str1);
    // console.log(output);



    // var regex = /\d321/
    // var str1 = "User Phone number is 987654a3210";

    // var output = regex.exec(str1);
    // console.log(output);


    // var regex = /\d+321/        // \d it works digit only
    // var str1 = "User Phone number is 9876543210";

    // var output = regex.exec(str1);
    // console.log(output);



    // var regex = /\d+321\d/        
    // var str1 = "User Phone number is 9876543210";

    // var output = regex.exec(str1);
    // console.log(output);


    // var regex = /\D+321\d/      
    // var str1 = "User Phone number is 987654a3210";

    // var output = regex.exec(str1);
    // console.log(output);


    // var regex = /\D+321\d/      
    // var str1 = "User Phone number is 987654$$3210";

    // var output = regex.exec(str1);
    // console.log(output);



    // var regex = /\D+321/      
    // var str1 = "User Phone number is 987654$$3210";

    // var output = regex.exec(str1);
    // console.log(output);



    // var regex = /\wber/      
    // var str1 = "User Phone number is 987654$$3210";

    // var output = regex.exec(str1);
    // console.log(output);


    // var regex = /\wber/      
    // var str1 = "User Phone num ber is 987654$$3210";

    // var output = regex.exec(str1);
    // console.log(output);


    // var regex = /\w+ber/      
    // var str1 = "User Phonenumber is 987654$$3210";

    // var output = regex.exec(str1);
    // console.log(output);


    // var regex = /\w+ber/      
    // var str1 = "User Phon^%%^enumber is 987654$$3210";

    // var output = regex.exec(str1);
    // console.log(output);

    // var regex = /\Wber/      
    // var str1 = "User Phonenumber is 987654$$3210";

    // var output = regex.exec(str1);
    // console.log(output);


    // var regex = /\Wber/      
    // var str1 = "User Phone number is 987654$$3210";

    // var output = regex.exec(str1);
    // console.log(output);




    // var regex = /\sphone/      
    // var str1 = "User Phone number is 9876543210";

    // var output = regex.exec(str1);
    // console.log(output);







 

 

40. This is user id and user password and DOB form validation

 

HTML Home Page

 
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <h1>This is Home page</h1>    
        <p>This is user id and user form validation</p>
    </body>
    </html>
 

 

HTML Form  page file

 
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <form action="homepage.html" onsubmit="return validate()">
        <input type="text" id="uname" placeholder="Username">
        <input type="password" id="pass" placeholder="password">
        <input type="number" id="age" placeholder="age">
        <input type="submit" value="submit">
        </form>
        <script src="validation.js" type="text/JavaScript">
        </script>    
    </body>
    </html>

   



JavaSript File

 
        function validate()
        {
            var uname = document.getElementById("uname").value;
            var pass = document.getElementById("pass").value;
            var age = document.getElementById("age").value;

            if(uname.trim == "" || pass.trim == "" || age.trim == "")
            {
                alert("Missing Credentials");
                return false;
            }

            else if(uname == "Kaushal" && pass == "1234" && age >= 13)
            {
                alert("Sign-up Successfully.")
                return true;
            }
            else if(age <13)
            {
                alert("Aged is not full fill by criteria.s")
                return false;
            }
            else
            {
                alert("Wrong Id and Password")
                return false;
            }

        }






41. Email validation

 

^ ---> caret charater

JS file
 
    function validate()
    {
        var email = document.getElementById("mail").value;
        var regex = /^([a-z A-Z 0-9 \. _]+)@([a-z A-Z]+).([a-z A-Z]{2,6})(.[a-z]{2,6})?$/

        if(email.trim()=="")
        {
            alert("Please enter a valid email id.")
        }
        else if((regex.test(email)))
        {
            alert("Email Submitted Successfully.");
        }
        else
        {
            alert("Wrong email id.");
        }

    }




HTML file
 
 
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <H1>Email  validation</H1>
        <script src="email.js" type="text/JavaScript"></script>
        <input type="email" id="mail" placeholder="Enter email Id.">
        <input type="button" value="Submit" onclick="validate()">
    </body>
    </html>
 
 


43. Debugging  Using chrome Developer 



44. Iterators and Generators in JavaScript

 iterator is an object that return an Object with two propertise.

 

 

 
    var arr = ["BMW","Audi","Mercedes","Jugar"];
    // console.log(arr);
    // console.log(arr.length);


    for(let i = 0; i < arr.length; i++){
        console.log(arr[i]);
    }

    // use above for loop using "for of" loop. same output.

    for(let i of arr)
    {
        console.log(i);
    }

    output:
        
    BMW
    Audi
    Mercedes
    Jugar
 


 

This is iterators (Keep in mind interviewer ask about it)

 
    function cars(values)
    {
        let index = 0;
        return{
            next: function(){   // next is a function here which will be call to print the current element value
                if(index < values.length)
                return{
               
                    value: values[index++],
                    done: false
                }
                else{
           
                    return{
                   
                        done: true
                    }
                }
            }
        }
    };

    var arr = ["BMW","Audi","Mercedes","Jugar"];

    var newCars = cars(arr);
    console.log(newCars.next())

     output:    
     
    Object { value: "BMW", done: false }
 
 
 

 

 

 



    function cars(values)
    {
        let index = 0;
        return{
            next: function(){   // next is a function here which will be call to print the current element value
                if(index < values.length)
                return{
               
                    value: values[index++],
                    done: false
                }
                else{
           
                    return{
                   
                        done: true
                    }
                }
            }
        }
    };

    var arr = ["BMW","Audi","Mercedes","Jugar"];


    var newCars = cars(arr);
    console.log(newCars.next())
    console.log(newCars.next())
    console.log(newCars.next())
    console.log(newCars.next())
    console.log(newCars.next())
 
    output:  
    




    Object { done: true } 
 
 

 

 

 
    function cars(values)
        {
            let index = 0;
            return{
                next: function(){   // next is a function here which will be call to print the current element value
                    if(index < values.length)
                    return{
                   
                        value: values[index++],
                        done: false
                    }
                    else{
               
                        return{
                       
                            done: true
                        }
                    }
                }
            }
        };

        var arr = ["BMW","Audi","Mercedes","Jugar"];





        var newCars = cars(arr);
        console.log(newCars.next().value)

   
        output:  BMW


 


    function cars(values)
    {
        let index = 0;
        return{
            next: function(){   // next is a function here which will be call to print the current element value
                if(index < values.length)
                return{
               
                    value: values[index++],
                    done: false
                }
                else{
           
                    return{
                   
                        done: true
                    }
                }
            }
        }
    };

    var arr = ["BMW","Audi","Mercedes","Jugar"];





    var newCars = cars(arr);
    console.log(newCars.next().value)
    console.log(newCars.next().value)
    console.log(newCars.next().value)
    console.log(newCars.next().value)
    console.log(newCars.next().value)
 
 
    output:
    BMW
    Audi
    Mercedes
    Jugar
    undefined 


 

 

Generator

Generator functions allow us to define an iterative algorithims by writing single non continuous function.

generator create with asteric (*) after function.

asteric tell  us this, this not a general function, this is generator function.





    function* generate()
    {
        let i = 0;
        yield "BMW";
        yield "Audi";
        yield "Mercedes";
        yield "Jugar";

    }

    let gen = generate()
    console.log(gen.next())
 
 
    output:  
    Object { value: "BMW", done: false }
 
 

 


    function* generate()
    {
        let i = 0;
        yield "BMW";
        yield "Audi";
        yield "Mercedes";
        yield "Jugar";

    }

    let gen = generate()
    console.log(gen.next())
    console.log(gen.next())
    console.log(gen.next())
    console.log(gen.next())
    console.log(gen.next())
 
 
    output:
    



    Object { value: undefined, done: true } 
 

 

 

 

 
    function* generate()
    {
        let i = 0;
        var ar = ["BMW", "Audi", "Mercedes","Jugar"]
        while(i<ar.length)
        {
            yield ar[i]
            i++;
        }

    }

    let gen = generate()
    console.log(gen.next())
 
    output:
    Object { value: "BMW", done: false } 
 

 

 

 
    function* generate()
    {
        let i = 0;
        var ar = ["BMW", "Audi", "Mercedes","Jugar"]
        while(i<ar.length)
        {
            yield ar[i]
            i++;
        }

    }

    let gen = generate()
    console.log(gen.next())
    console.log(gen.next())
    console.log(gen.next())
    console.log(gen.next())
    console.log(gen.next())
 
    output: 
 
    



    Object { value: undefined, done: true }
 
 

 

 


    function* generate()
    {
        let i = 0;
        var ar = ["BMW", "Audi", "Mercedes","Jugar"]
        while(i<ar.length)
        {
            yield ar[i]
            i++;
        }

    }


    let gen = generate()
    console.log(gen.next().value)
    console.log(gen.next().value)
    console.log(gen.next().value)
    console.log(gen.next().value)
    console.log(gen.next().value)
      
    output: 
 
    BMW
    Audi
    Mercedes
    Jugar
    undefined 
 
 

 

 

45. Maps

Maps and Object are same but little different.

 
    var myCar = new Object()
    {
        myCar.manufacturer ="Ford";
        myCar.name = "Raptor";
        myCar.color = "Black";
    }

    // console.log(myCar);
    // console.log(myCar.color);

    myCar.make = 2012;
    console.log(myCar);
 
 

 


    // This is an empty Object

    var myName = new Object()
    {

    }


 

 

 
    // This is an empty Map
    var myNmae = new Map()
    {

    }


 

 

 
    // This is  Map
    var myNmae = new Map()
    {
        myNmae.set(1,"BMW")
        myNmae.set(2,"Audi")
        myNmae.set(3,"Mercedes")
    }
    console.log(myNmae);


 

 

 
    var myNmae = new Map()
    {
        myNmae.set(1,"BMW")
        myNmae.set(2,"Audi")
        myNmae.set(3,"Mercedes")
    }
    // console.log(myNmae);

    // This is  Map with get method
    console.log(myNmae.get(3))


 

 


    // This is  Map with set method
    var myNmae = new Map()
    {
        myNmae.set(1,"BMW")
        myNmae.set(2,"Audi")
        myNmae.set(3,"Mercedes")
    }
    // console.log(myNmae);

    // This is  Map with get method
    // console.log(myNmae.get(3))

    // map size function
    console.log(myNmae.size);


 

 


    var myNmae = new Map()
    {
        myNmae.set("My car name is", "Jugar");
        myNmae.set({}, "Honda");
        myNmae.set(function (){}, "Mercedes");
    }
    console.log(myNmae)



 

 


    var myNmae = new Map()
    var obj = {};
    let func = function (){}


    {
        myNmae.set("My car name is", "Jugar");
        myNmae.set(obj, "Honda");
        myNmae.set(func, "Mercedes");
    }
    console.log(myNmae.get(func))



 

 
    var myNmae = new Map()
    var obj = {};
    let func = function (){}


    {
        myNmae.set("My car name is", "Jugar");
        myNmae.set(obj, "Honda");
        myNmae.set(func, "Mercedes");
    }
    console.log(myNmae.get(obj))




 

 



    var myarr = [[1, "BMW"], [2, "Audi"],[3,"Honda"]]
    var myCar = new Map(myarr)

    console.log(myCar.get(2));
 
 

 

 using for Loop

 
    var myarr = [[1, "BMW"], [2, "Audi"],[3,"Honda"]]
    var myCar = new Map(myarr)

    console.log(myCar.get(2));

    for(let [key,value] of myCar)
    {
        console.log(key + " " + value);
       
    }



 

 


    var myarr = [[1, "BMW"], [2, "Audi"],[3,"Honda"]]
    var myCar = new Map(myarr)

    console.log(myCar.get(2));

    for(let [key,value] of myCar)
    {
        console.log(key);
       
    }


 

we can clone using map



    var myarr = [[1, "BMW"], [2, "Audi"],[3,"Honda"]]
    var myCar = new Map(myarr)


    var yourCar = new Map(myCar)
    console.log(yourCar)



 

 

46. Set 

set in javacript is an Object. Set similar to map in javascript. It ,it meams they are
also an Object but they perform various activity other than Map. Syntax is also same and even propertise are also same.  

Set strore Unique Value.

 

This is the syntax of set in JavaScript

 
    var myset = new Set()
 


 
    var myset = new Set()
    console.log(myset);
 
    output:     
    Set []


 

 

 
    var myset = new Set()
    myset.add(1)
    myset.add(2)
    myset.add(3)
    myset.add(4)
    myset.add(3)    // SET NOT ALLOWED 3 AGAIN
    console.log(myset);
 
     output: 
     Set(4) [ 1, 2, 3, 4 ] 



 

 


    let arr = [1,2,3,4,3,45,3,5,6,2,3,2]

    let myset2 = new Set(arr)
    console.log(myset2);
   
     output: Set(7) [ 1, 2, 3, 4, 45, 5, 6 ]
 

 


    let arr = [1,2,3,4,3,45,3,5,6,2,3,2]

    let myset2 = new Set(arr)
    console.log(myset2);

    let myArr = Array.from(myset2)
    console.log(myArr);
 
    outpt: 
    

    Array(7) [ 1, 2, 3, 4, 45, 5, 6 ] 
 

 

 


    let arr = [1,2,3,4,3,45,3,5,6,2,3,2]

    let myset2 = new Set(arr)
    console.log(myset2);

    let myArr = Array.from(myset2)
    console.log(myArr);

    for(let item of myset2)
    console.log(item)
   
 
    Output: 


    1
    2
    3
    4
    45
    5
    6
  


 

 
    let arr = [1,2,3,4,3,45,3,5,6,2,3,2]
    let myset2 = new Set(arr)


    //  delete a set
    myset2.delete(45)
    console.log(myset2);
 
    output:   
    Set(6) [ 1, 2, 3, 4, 5, 6 ]
 

 

 
    let arr = [1,2,3,4,3,45,3,5,6,2,3,2]
    let myset2 = new Set(arr)


    myset2.clear();
    console.log(myset2);
 
 
     output:  
     Set []
 
 

 

 

47. Flopply  Bird Games


Html File

 

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Flappy Birds</title>
        <link rel="stylesheet" href="flappyzBird.css">
    </head>
    <body>
        <div id="game">
            <div id="block"></div>
            <div id="hole"></div>
            <div id="bird"><img src="bird2.png" alt="Bird"> </div>
        </div>
        <div id="result">
            <h1>Game Over</h1>
            <p id="text"></p>
            <button id="btn" onclick="location.reload()">Restart</button>
        </div>

        <script src="flappyBird.js"></script>
       
    </body>
    </html>
 

 

CSS file 

 

    *{
        margin: 0;
        padding: 0;
    }

    body
    {
        background-color: cadetblue;
        background-image: -webkit-linear-gradient(rgb(175,75,75), rgb(31,31,31),rgb(59,153,148));
        min-height: 800px;
    }

    #game
    {
        height: 500px;
        width: 400px;
        border: 1px solid black;
        background: url(bg1.jpg);
        background-size: cover;
        margin: 1rem auto;
        overflow: hidden;
    }

    #block
    {
        width: 50px;
        height: 500px;
        background-color: rgb(15, 17, 15);
        position: relative;
        left: 400px;
        animation: block 2s linear infinite;
    }

    @keyframes block{
        0%{
            left: 400px;
        }
        100%{
            left: -50px;
        }
    }

    #hole{
        height: 150px;
        width: 50px;
        background-color: rgb(250, 155, 2);
        position: relative;
        left: 400px;
        top: -500px;
        animation: block 2s linear infinite;
    }

    #bird
    {
        position: fixed;
        top: 100px;
        height: 50px;
        width: 50px;
    }

    #bird img
    {
        height: 50px;
        width: 50px;

    }

    #result{
        height: 200px;
        width: 500px;
        background-color: brown;
        margin: 5rem auto;
        border: 2px solid white;
        border-radius: 20px;
        display: none;
        text-align: center;
    }

    #btn{
        padding: 0.5 rem 1rem;
        border: none;
        border-radius: 11px;
        background-color: rgb(63, 53, 53);
        color: white;
        font-size: 1.5 rem;
        text-transform: uppercase;
        margin-top: 1rem;
        cursor: pointer;

    }

    #text{
        margin: 1rem;
        font-size: 2rem;
        color: seashell;
    }
 

 

 

 JS File

 
    var hole = document.getElementById("hole");
    var game = document.getElementById("game");
    var result = document.getElementById("result");
    var text =  document.getElementById("text");
    var score = 0;
    var jumping = 0;

    hole.addEventListener("animationiteration", RanHole)

    function RanHole(){
        var random = -((Math.random()*350)+150)
        hole.style.top = random+"px";
        score++  
    }  

    var fall = setInterval(function(){
        var birdTop = parseInt(window.getComputedStyle(bird).getPropertyValue("top"));
        if(jumping ==0)
        {
            bird.style.top = (birdTop+2)+"px";
        }
        var blockLeft =parseInt(window.getComputedStyle(block).getPropertyValue("left"))
        var holeTop = parseInt(window.getComputedStyle(hole).getPropertyValue("top"));
        var hTop = (500+holeTop)
        if((birdTop >450) || ((blockLeft<50)&& ((birdTop < hTop ||(birdTop > hTop + 100)))))
        {
            result.style.display = "block";
            text.innerText = `your final score is : ${score}`;
            game.style.display = "none";
            score = 0;
        }
    },10)


    window.addEventListener("keydown",hop)
    function hop()
    {
        jumping = 1;

        var birdTop = parseInt(window.getComputedStyle(bird).getPropertyValue("top"))
        if(birdTop > 6)
        {
            bird.style.top = (birdTop - 60) + "px";
        }

        setTimeout(function(){
            jumping = 0
        },100)
    }




 

 

48. Website  Book Selling Project By JS

 JS File

 
    const cart = document.querySelector("nav .cart")
 
    var cartSidebar = document.querySelector(".cart-Sidebar")
    const closeCart = document.querySelector(".close-cart")
    const burger = document.querySelector(".burger")
    const menuSidebar = document.querySelector(".menu-sidebar")
    const closeMenu = document.querySelector(".close-menu")
    const cartItemsTotal = document.querySelector("noi")
    const cartPriceTotal = document.querySelector(".total-amount")
    const cartUi = document.querySelector(".cart-sidebar .cart")
    const totalDiv = document.querySelector(".total-sum")
    const clearBtn = document.querySelector(".clear-cart-btn")
    const cartContent = document.querySelector(".cart-content")


    let Cart = [];
    let buttonsDOM = [];

    cart.addEventListener("click", function () {
        cartSidebar.style.transform = "translate(0%)"
        const bodyOverlay = document.createElement("div")
        bodyOverlay.classList.add("overlay");
        setTimeout(function () {
            document.querySelector("body").append(bodyOverlay)
        }, 300)
    })

    closeCart.addEventListener("click", function () {
        cartSidebar.style.transform = "translate(100%)"
        const bodyOverlay = document.querySelector(".overlay")
        document.querySelector("body").removeChild(bodyOverlay)
    })


    burger.addEventListener("click", function () {
        menuSidebar.style.transform = "translate(0%)"
    })


    closeMenu.addEventListener("click", function () {
        menuSidebar.style.transform = "translate(-100%)"
    })


    class Product {
        async getProduct() {
            const response = await fetch("product.json");
            const data = await response.json();
            let products = data.items;
            products = products.map(item => {
                const { title, price } = item.fields;
                const { id } = item.sys;
                const image = item.fields.image.fields.file.url;
                return { title, price, id, image };
            })
            return products;
        }
    }

    class UI {
        displayProducts(products) {
            let result = "";
            products.forEach(product => {
                const productDiv = document.createElement("div")
                productDiv.innerHTML = `<div class = "product-card">
                                        <img src="${product.image}" alt="product">
                                        <span class= "add-to-cart" data-id="${product.id}">
                                        <i class = "fa fa-cart--plus fa-1x"
                            style = "margin-right:0.1em; font-size:1em;"></i>
                                    add to cart
                                    </span>
                                    <div class= "product-name">${product.title} </div>
                                    <div class= "product-pricing">${product.price}
                                    </div>`
                const p = document.querySelector(".product")
                p.append(productDiv)

            })
        }
    }

    getButtons()
    {
        const btns = document.querySelectorAll(".add-to-cart")
        Array.from(btns)
        buttonsDOM = btns;
        btns.forEach((btn) => {
            let id = btn.dataset.id
            let inCart = Cart.find((item) => item.id === id);
            if (inCart) {
                btn.innerHTML = "In Cart"
                btn.dissabled = true
            }
            btn.addEventListener("click", (e) => {
                e.currentTarget.innerHTML = "In Cart"
                e.currentTarget.style.color = "white"
                e.currentTarget.style.pointerEvents = "none"
                let cartItem = { ...Storage.getStorageProducts(id), 'amount': 1 }
                Cart.push(cartItem)
                Storage.saveCart(Cart)
                this.setCartValues(Cart)
                this.addCartItem(cartItem)
            })
        })
    }

    setCartValues(cart)
    {
        let tempTotal = 0;
        let itemTotal = 0;
        Cart.map((item) => {
            tempTotal += (item.price * item.amount);
            itemTotal += item.amount;
            parseFloat(tempTotal.toFixed(2))
        })
        cartItemsTotal.innerHTML = itemsTotal
        cartPriceTotal.innerHTML = parseFloat(tempTotal.toFixed(2))
    }

    addCartItem(cartItem)
    {
        let cartItemUi = document.createElement("div")
        cartItemUi.innerHTML = `<div class= "cart-product">
                                <div class = "product-image">
                                    <img src = "${cartItem.image} alt="product">
                                    </div>
                                    <div class = "cart-product-content">
                                    <div class = "cart-product-name"><h3>${cartItem.title}</h3></div>
                                    <div
                                    class= "cart-product-price"><h3>${cartitem.price}</h3></div>
                                    <div class= "cart-product-remove data-id="${cartItem.id}"
                                    href="#" style="color:red;>remove</a></div>
                                    </div>
                                    <div class= "plus-minus">
                                    <i class = "fa fa-angle-left add-amount"
                                    data-id="${cartItem.id}"></i>
                                    <span class="no-of-items">${cartItem.amount}</span>
                                    data-id="${cartItem.id}"</i>
                                    </div>
                                    </div>`
        cartContent.append(cartItemUi)

    }
    setupApp()
    {
        Cart = Storage.getCart()
        this.setCartValues(Cart)
        Cart.map((item) => {
            this.addCartItem(item)
        })
    }
    cartLogic()
    {
        clearBtn.addEventListener("click", () => {
            this.closeCart()
        })
        cartContent.addEventListener.apply("click", (event) => {
            if (event.target.classList.contains("cart-product-remove")) {
                let id = event.target.dataset.id
                this.remobeItem(id)
                let div = event.target.parentElement.parentElement.parentElement.parentElement
                div.removeChild(event.target.parentElement.parentElement.parentElement.parentElement)

            }
            else if (event.target.classList.contains("add-amount")) {
                let id = event.target.dataset.id
                let item = Cart.find((item) => item.id === id)
                item.amount++
                Storage.saveCart(Cart)
                this.setCartValues(Cart)
                event.target.nextElemetSibling.innerHTML = item.amount
            }
            else if (event.target.classList.contains("reduce-amount")) {
                let id = event.target.dataset.id
                let item = Cart.find((item) => item.id === id)
                if (item.amount > 1) {
                    item.amount--
                    Storage.saveCart(Cart)
                    this.setCartValues(Cart)
                    event.target.previousElementSibling.innerHTML = item.amount
                }
                else {
                    this.remobeItem(id)
                    let div = event.target.parentElement.parentElement.parentElement.parentElement
                    div.removeChild(event.target.parentElement.parentElement.parentElement.parentElement)

                }
            }
        })
    }

    addAmount()
    {
        const addBtn = document.querySelectorAll(".add-amount")
        addBtn.forEach((btn) => {
            btn.addEventListener("click", (event) => {
                let id = (event.currentTarget.dataset.id)
                Cart.map((item) => {
                    if (item.id === id) {
                        item.amount++
                        Storage.saveCart(Cart)
                        this.setCartValues(Cart)
                        const amountUi = event.currentTarget.parentElement.children[1]
                        amountUi.innerHTML = item.amount
                    }
                })
            })
        })
    }
    reduceAmount()
    {
        const reduceBtn = document.querySelectorAll(".reduce-amount")
        reduceBtn.forEach((btn) => {
            btn.addEventListener("click", (event) => {
                let id = (event.currentTarget.dataset.id)
                Cart.map((item) => {
                    if (item.id === id) {
                        item.amount--
                        if (item.amount > 0) {
                            Storage.saveCart(Cart)
                            this.setCartValues(Cart)
                            const amountUi = event.currentTarget.parentElement.children[1]
                            amountUi.innerHTML = item.amount
                        } else {
                            event.currentTarget.parentElement.parentElement.parentElement.removeChild(event.currentTarget.parentElement.parentElement)
                            this.removeItem(id)
                        }

                    }
                })
            })
        })
    }
    closeCart()
    {
        let cartItem = Cart.map(item => item.id)
        cartItem.forEach((id) => this.removeItem(id))
        const cartProduct = document.querySelectorAll(".cart-product")
        cartProduct.forEach((item) => {
            if (item) {
                item.parentElement.removeChild(item)
            }
        })
    }
    removeItem(id)
    {
        Cart = Cart.filter((item) => item.id !== id)
        this.setCartValues(Cart)
        Storage.saveCart(Cart)
        let button = this.getSingleButton(id)
        button.style.pointerEvents = "unset"
        button.innerHTML = `<i class= "fa fa-cart-plus"></i> Add To Cart`
    }
    getSingleButton(id)
    {
        let btn
        buttonsDOM.forEach((button) => {
            if (button.dataset.id === id) {
                btn = button
            }
            return btn
        })
       
    }

    class Storage{
        static saveProducts(products){
            localStorage.setItem("products",JSON.stringify(products))
        }
        static getStorageProducts(id){
            let products= JSON.parse(localStorage.getItem('products'))
            return products.find((item)=>item.id===id)
        }
        static saveCart(Cart){
            localStorage.setItem('Cart',JSON.stringify(Cart))
        }
        static getCart(){
            return loocalStorage.getItem('Cart')? JSON.parse(localStorage.getItem("Cart")):[]
        }
    }


    document.addEventListener("DOMContentLoaded",()=>{
        const products = new Products();
        const ui = new UI();
        ui.setupApp()
        products.getProduct().then(products=>{
            ui.displayProducts(products)
            Storage.saveProducts(products)
        }).then(()=>{
            ui.getButtons();
            ui.cartLogic();
        })
    })
 

 

CSS File

 
    *{
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        font-size: 20px;
    }

    html{
        scroll-behavior: smooth;
    }

    a{
        text-decoration: none;
    }

    ul{
        list-style: none;
    }

    .navbar{
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 10vh;
        background-color: white;
    }

    .logo{
        padding-left: 2em;
    }

    .logo-text{
        font-size: 2em;
    }

    .menubar{
        width: 45%;
        margin-left: 8.5em;
    }

    .list{
        display: flex;
        justify-content: space-between;
    }

    .list-items a{
        color: black;
        font-family: sans-serif;
        font-size: 0.9em;
        transition: 0.4s;
    }

    .list-items a:hover{
        color: black;
    }

    .cart{
        padding-right: 2em;
        position: relative;
    }

    .cart .number-of-items{
        display: flex;
        cursor: pointer;
        justify-content: center;
        align-items: center;
        color: white;
        position: absolute;
        left: 18px;
        top: -7px;
        background: #f09d51;
        height: 20px;
        width: 20px;
        border-radius: 7px;
       
    }

    .number-of-items .noi{
        font-size: 0.7em;
    }

    .fa-shopping-cart{
        font-size: 1.5em;
        cursor: pointer;
    }

    .burger{
        height: 28px;
        width: 32px;
        display: none;
    }

    .layer1, .layer2,.layer3{
        background: black;
        height: 4px;
        margin-top: 4px;
        width: 100%;
        border-radius: 10px;
    }

    .section1{
        height: calc(100vh - 10vh);
        width: 100%;
        background: url("back3.jpg") center center/cover;
        top: 0;
        left: 0;
        z-index: -1;

    }

    .section1 .banner{
        height: 170px;
        width: 600px;
        background: rgba(255,255,255,0.7);
        position: relative;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        display: flex;
        justify-content: space-around;
        flex-direction: column;
        text-align: center;
        align-items: center;
        font-family: sans-serif;
        z-index: 8;
    }

    .banner h1{
        font-size: 2em;
    }

    .banner a{
        display: flex;
        justify-content: center;
        padding: 1em 2.5em;
        font-size: 0.8em;
        color: white;
        background: #f09d51;
        transition: all 0.3s;
    }

    .banner a:hover{
        background: hsl(120, 85%, 43%);

    }

    .section2.title{
        text-align: center;
    }

    .section2 .title h1{
        font-size: 1.8em;
        margin: 1.3em;
    }

    .product{
        margin: 0.5em auto;
        max-width: 1300px;
        display: grid;
        grid-column-gap: 2em;
        grid-row-gap: 2em;
        grid-template-columns: repeat(auto-fit, minmax(350px,1fr));
    }
    .product-card{
        text-align: center;
        position: relative;
        max-width: 350px;
        overflow: hidden;

    }

    .product-card img{
        height: 300px;
        width: 300px;
        transition: 0.3s linear;
    }

    .product-name,.product-pricing{
        margin: 0.3em;
    }

    .product-pricing{
        color: #f09d51;
    }

    .add-to-cart{
        align-items: center;
        justify-content: center;
        color: white;
        padding: 0.2em 1em;
        height: 30px;
        background: #f09d51;
        right: 0;
        transform: translateX(100%);
        bottom: 80px;
        transition: 03s linear;
        cursor: pointer;
    }

    .product-card:hover .add-to-cart{
        transform: translate(0%);
    }

    .product-card:hover img{
        opacity: 0.7;
    }

    .add-to-cart:hover{
        color: black;
    }

    /* menubar */

    .menu-sidebar{
        display: none;
    }

    .cart-sidebar{
        background: #ececec;
        position: fixed;
        right: 0;
        top: 0;
        width: 450px;
        height: 100vh;
        z-index: 10;
        transition: all 0.3s linear;
        transform: translateX(100%);
        overflow: scroll;
    }


    .cart-sidebar .cart{
        padding: 0;
    }

    .cart .close-cart{
        font-size: 1.3em;
        padding: 1em;
        cursor: pointer;
    }

    .fa-times{
        margin-top: 0.5em;
    }

    cart h2{
        text-align: center;
        width: 100%;
        margin-bottom: 1em;
        font-size: 1.1em;
        font-family: Verdana;
    }

    .cart-product .product-image img{
        width: 130px;
        height: 90px;
    }

    .cart-product-contnent{
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        align-items: center;
        margin-left: 1em;
        height: 80px;
    }


    .plus-minus{
        display: flex;
        transform: rotate(90deg);
        color: #f09d51;
        font-size: 1.5em;
        cursor: pointer;  
    }

    .total-sum{
        text-align: center;
        margin: 1em 0 0.5em 0;
    }

    .clear-cart{
        text-align: center;
    }

    .clear-cart .btn{
        background-color: #d4761e;
        color: white;
        border: 1px solid white;
        padding: 0.5em 1.7em;
        cursor: pointer;
        transition: 0.3s linear;
    }

    .clear-cart .btn:hover{
        border: 1px solid #d4761e;
        background: transparent;
        color: black;
    }

    .overlay{
        height: 100vh;
        position: fixed;
        top: 0;
        left: 0;
        z-index: 9;
        width: 100%;
        background-color: #f3851f;
        opacity: 0.3;
        transition: all 0.3s linear;
    }

    .none{
        display: none;
    }

    @media screen and (max-width:768px){
        .logo{
            padding-left: 0;
        }
        .cart{
            padding-right: 2em;
        }
        .menubar{
            display: none;
        }
        .burger{
            margin-left: 2em;
            display: block;
        }
        .section1 .banner h1{
            font-size: 1.5em;
        }
        .banner a{
            font-size: 0.6em;
            padding: 1em 2em;
        }
        .section2 .title h1{
            font-size: 1.5em;
        }
        .menu-sidebar{
            display: block;
            position: fixed;
            left: 0;
            top: 0;
            width: 100%;
            height: 100vh;
            z-index: 11;
            background: #ececec;
            overflow: hidden;
            transform: translate(-100%);
            transition: 0.3s linear;
        }
        .menu-menubar{
            display: flex;
            height: 80%;
            justify-content: center;
        }

        .menu-list{
            height: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: space-around;
        }
        .menu-sidebar .close-menu{
            position: absolute;
            right: 30px;
            font-size: 1.4em;
        }
        .menu-list-items a{
            color: #f09d51;
        }
        .menu-list-items a:hover{
            color: #f57b09;
        }

    }


    @media screen and (max-width:480px){
        *{
            font-size: 16px;
        }
        .section1 .banner{
            width: 280px;
            height: 100px;
        }

        .section1 .banner h1{
            font-size: 1.2em;
        }

        .burger{
            margin-left: 1em;
            display: block;
            width: 30px;
        }
        .cart-sidebar{
            width: 100%;
        }
        .product{
            margin: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
        }
    }




 

JSON File

    {
    "items":
        [
            {
                "sys":{"id": "1"},
                "fields":{
                    "title": "Python proramming Master course.",
                    "price": 1234.99,
                    "image":{"fields":{"file":{"url":"back1.jpg"}}}
                }
            },
            {
                "sys":{"id": "2"},
                "fields":{
                    "title": "Java proramming Master course.",
                    "price": 1234.99,
                    "image":{"fields":{"file":{"url":"back1.jpg"}}}
                }
            },
            {
                "sys":{"id": "3"},
                "fields":{
                    "title": "Web Development.",
                    "price": 14.99,
                    "image":{"fields":{"file":{"url":"back1.jpg"}}}
                }
            },
            {
                "sys":{"id": "4"},
                "fields":{
                    "title": "Machine Learning Master course.",
                    "price": 541.99,
                    "image":{"fields":{"file":{"url":"back1.jpg"}}}
                }
            },
            {
                "sys":{"id": "5"},
                "fields":{
                    "title": "Data Structure and Algorithms.",
                    "price": 954.99,
                    "image":{"fields":{"file":{"url":"back1.jpg"}}}
                }
            },
            {
                "sys":{"id": "6"},
                "fields":{
                    "title": "Cyber Security.",
                    "price": 484.99,
                    "image":{"fields":{"file":{"url":"back1.jpg"}}}
                }
            },
            {
                "sys":{"id": "7"},
                "fields":{
                    "title": "Data Analysis.",
                    "price": 554.99,
                    "image":{"fields":{"file":{"url":"back1.jpg"}}}
                }
            }
           
           
           
        ]
    }
 

 HTML File

 
        <!DOCTYPE html>
        <html lang="en">

        <head>
            <meta charset="UTF-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
            <link rel="stylesheet" type="text/css" href="webpage.css">
            <title>Document</title>
        </head>

        <body>

            <nav class="navbar">
                <div class="burger">
                    <div class="layer1"></div>
                    <div class="layer2"></div>
                    <div class="layer3"></div>
                </div>
                <div class="logo">
                    <span class="logo-text"><i class="fa fa-book" style="margin-right: 0.1em"></i>Comfort<span
                            style="color:#f095d1" ; font-size: 1.1em;>Learning</span>
                </div>

                <div class="menubar">
                    <ul class="list">
                        <li class="list-items"><a href="#">Home</a></li>
                        <li class="list-items"><a href="#">Courses</a></li>
                        <li class="list-items"><a href="#">Pricing</a></li>
                        <li class="list-items"><a href="#">About Us</a></li>
                    </ul>
                </div>
                <div class="cart">
                    <i class="fa fa-shopping-cart fa-1x"></i>
                    <div class="number-of-items"><span class="noi">0</span></div>

                </div>

            </nav>

            <section class="section1">
                <div class="banner">
                    <h1>Find your favorite courses here</h1>
                    <a href="#product">Shop Now</a>
                </div>
            </section>

            <section class="section 2" id="products">
                <div class="title">
                    <h1>Courses We Offer!</h1>
                </div>
                <div class="product">

                </div>
            </section>

            <div class="cart-sidebar">
                <div class="cart">
                    <span class="close-cart">
                        <i class="fa fa-times"></i>
                    </span>
                    <h2>Your cart</h2>
                    <div class="cart-content"></div>
                </div>
                <div class="total-sum"></div>
                <h1>Your total: $ <span class="total-amount">0</span></h1>
            </div>
            <div class="clear-cart">
                <button class="btn clear-cart btn">Clear Cart</button>
            </div>
            <div class="clear-cart">
                <button class="btn clear-cart-btn">Proceed</button>
            </div>
            </div>
            </div>


            <div class="menu-sidebar">
                <div class="close-menu">
                    <i class="fa fa-times"></i>
                </div>
                <div class="menu-menubar">
                    <ul class="menu-list">
                        <li class="menu-list-items"><a href="#">Home</a></li>
                        <li class="menu-list-items"><a href="#">Category</a></li>
                        <li class="menu-list-items"><a href="#">Price</a></li>
                        <li class="menu-list-items"><a href="#">About</a></li>
                    </ul>
                </div>
            </div>
            <script src="webpage.js" type="text/javascript"></script>
            <script src="webpage.json" type="text/javascript"></script>
        </body>

        </html>
 

    6 to 14 march taken to completed

Post a Comment (0)
Previous Post Next Post