Learn and Practice Javascript

DAY 1: 25 OCT 2022

 
<HTML>

<Head>
    <Title> Learning HTML AND JAVASCRIPT</Title>

    <Script>
        //displaying a welcome message

        /*
        3 ways to use numbers
        1. var
        2. let
        3. const
   
        */
        //var examples – older version of javascript
        var num3 = 50
        var num4 = 90
        var sum1 = num3 + num4

        //let is used in the newer version
        let name = Sachin //declaring and assigning value to a variable
        let num1 = 50
        let num2 = 60
        num1 = 40
        let sum = num1 + num2

        //Const
        const pi = 3.14
        //pi = 4

        /*
        Creating a welcome message for the website’s reader
        thank you
        go ahead
        */
        msg = Welcome to Javascript learning Session + name

        //usage of  ‘  ‘  and ”  “
        let str1 = Hello  //string datatype
        let str2 = How are you?;
        // let’s go
        str1 = let’s go;
        // he said,”Whats you name?”
        str2 = he said,”Whats you name?” ;

        //boolean: true and false
        num1 = 80
        num2 = 60
        num1 == num2  //false

        num1 < num2  // true
        if (num1 < num2) alert(Num1 is smaller than num2);

        alert(msg)

        //array
        let array1 = [JAN, Feb, Mar]

        //Object data type
        let obj1 = { fname: Sachin, lname: Tendulkar, runs: 25000, sports: Cricket }
        // datatype is object

        sum = 12 + 24 + 36 + hello

        //Datatype in Javascript is dynamic in nature
        let x  //variable is declared but not defined (defined = has to have a datatype)
        x = 99  // number datatype
        x = [JAN, Feb, Mar]  //will not throw error – dynamically typed data

        //numbers with scientific notation (e)
        let y = 99e6 //99000000
        let z = 9.9e7
        //alert(z)
        let t = 5.5e-3  //  0.0055
        alert(t)

        // typeof will give the datatype
        alert(typeof x)
        alert(typeof (y))
        let var4   //undefined
        alert(typeof (var4))

    </Script>

</Head>

<Body>

    Hello everyone, how are you doing?

</Body>

</HTML>

Day 2: 26 OCT 2022


<HTML>

<Head>
    <Title> Learning 2</Title>


    <Script>
        //declare a function
        function mysum(n1, n2, n3) {
            let total
            total = n1 + n2 + n3
            return total
        }
        //num1 = total – error: notdefined as its local variable
        let result = mysum(11, 22, 33)
        alert(Sum is + mysum(11, 22, 33))

        /*
            avg >=80 – Grade A
            avg >=60 (<80) – Grade B
            avg >=40 – Grade C
            avg <40 – Grade D
        */
        let avg = 95

        if (avg >= 80) {
            //what happens if the condition is true
            alert(Grade A)
        } else if (avg >= 60) {
            alert(Grade B)
        } else if (avg >= 40) {
            alert(Grade C)
        } else {
            alert(Grade D)
        }

        // SWITCH – also used for conditions
        //  Date()  – inbuilt function to get the date, getDay() will the day in integer value
        // 0 for Sunday, 1 for Monday …
        dayval = new Date().getDay()  //day in number
        switch (dayval) {
            case 2:
                alert(Today is Tuesday)
                break
            case 0:
                alert(Today is Sunday)
                break
            case 1:
                alert(Today is Monday)
                break

            case 3:
                alert(Today is Wednesday)
                break
            case 4:
                alert(Today is Thursday)
                break
            case 5:

            case 6:
                alert(It could be Friday or Saturday)
                break
            default:
                alert(I Dont Know the Day)
                break
        }

        /*
        Loops in Javascript: There are multiple types:
        1. for
        2. for /in – iterated through the properties of object
        3. for /out – iterated through the values of object

        4. while – is entry controlled loop
        5. do/while – is exit controlled loop
        */

        //for loop
        for (let i = 0; i < 5; i++) {
            alert(Loop is running : + i)
        }
    </Script>

</Head>

<body>

</body>

</HTML>

Day 3: For Loop

<html>

<head>
    <script>
        /*
        Loops in Javascript: There are multiple types:
        1. for
        2. for /in – iterated through the properties of object
        3. for /of – iterated through the values of object

        4. while – is entry controlled loop
        5. do/while – is exit controlled loop
        */

        //for loop
        let i = 1
        for (; i < 5; i++) {
            alert(Loop is running : + i)
        }

        i = 1
        for (; i < 1; i++) {
            alert(Loop is running : + i)
        }

        let obj1 = { fname: Sachin, lname: Tendulkar, runs: 25000, sports: Cricket }
        for (let j in obj1) {
            alert(j = + j + and value is + obj1[j])

        }
        let runs = [102, 2, 97, 0, 95]
        for (let j in runs) {
            alert(j = + j + and value is + runs[j])
        }
        /*
        of is not iteratable on Object
        for (let j of obj1) {
            alert(“j = ” + j)

        }
        */
        name = Sachin
        for (let j of name) {
            alert(j = + j)

        }

        //Creating a function to demonstrate forEach() of array
        /*
        it takes 3 arguments: item value, index and the array
        */
        runs = [102, 2, 97, 0, 95]
        let out_val = “”
        let ind_val = “”
        let array_val = “”

        runs.forEach(func_array)

        function func_array(val, index, array) {
            out_val += val + ,
            ind_val += index + ,
            array_val += array + ,
        }
        alert(Output of the function is: Value = + out_val + index = + ind_val + array = + array_val)
    </script>
</head>

<body>

</body>

</html>

DAY 4: WHILE

<html>

<head>
    <script>
        runs = [102, 2, 97, 0, 95]
        let out_val = 0
        let ind_val = 0
        let array_val = 0

        runs.forEach(func_array)

        function func_array(val, index, array) {
            out_val += val
            ind_val += index + ,
            if (index < 1) {
                array_val = array
            }

        }
        alert(Output of the function is: Sum of Value = + out_val + index = + ind_val + array = + array_val)
        // If is used when you know how many times to repeat
        //While works on conditions – while will repeat if the condition is True
        let a = 0
        while (a < 10) {
            alert(a)
            a += 2
        }
        //while is entry controlled loop
        a = true
        let num = 10
        while (a) {
            alert(num)
            num += 10
            if (num > 50) {
                break
            }
        }
        // do while – exit controlled
        num = 10
        do {
            alert(Second Run + num)
            num += 10
        }
        while (num < 0)

        //iterating through an array
        let players = [Sachin, Rohit, Rahul, Kapil, Kohli]
        let all_players = “”
        let counter = 0
        while (players[counter]) {
            all_players += players[counter] +
            counter += 1
        }
        alert(all_players)
        // a + = num   => a = a + num

        //Map Declaration
        runs_scored = new Map([
            [Sachin, 19000],
            [Kapil, 11000],
            [Sunil, 18000]
        ])

        //get() to fetch the data
        alert(Runs scored by Sunil is + runs_scored.get(Sunil))

        //set – add value to existing map
        runs_scored.set(Virat, 8900)
        alert(Runs scored by Virat is + runs_scored.get(Virat))
    </script>
</head>
<body>
</body>
</html>

DAY 5

<html>

<head>
    <script>
        //MAPS
        // new Map() – create a new map
        //set() – to add member
        //get() – get the value from the map

        players = new Map([
            [Sachin, 19000],
            [Rohit, 11000,],
            [Kapil, 9000],
            [Sunil, 18800]
        ])
        key_to_delete = Sachin
        alert(players.has(key_to_delete))
        if (players.has(key_to_delete)) {
            players.delete(key_to_delete)
        }
        players.set(Dhoni, 13000)
        alert(Size of the players map is + players.size)
        //if I want to iterate through : forEach
        let check = 0
        players.forEach(function (value, key) {
            if (key == Dhoni) {
                check = 1
            }
        })
        if (check == 0) {
            alert(Dhoni is not in the map)
        } else {
            alert(Dhoni is in the map)
        }

        // entries: get you all the entries
        //iterate through each key and value pair
        alert(players.entries :)
        for (let x of players.entries()) {
            alert(x)
        }
    </script>
</head>

<body>
</body>

</html>

DAY 6

<html>

<head>
    <title> My Website</title>
    <script>
        let a = 5
        debugger
        let b = 6
        //debugger
        c = a + b
        //debugger
        console.log(c)

        // arrow function
        let myfunction = (x, y, z) => 2 * x y + 0.38 * z

        let val = myfunction(5, 8, 100)
        //alert(val)
        console.log(val)

        class Laptop {
            //class level variables
            total = 0
            //class level methods

            //object level method
            constructor(person, make, os, year) {
                this.person = person
                this.make_co = make  //object level variables
                this.os = os
                this.purchase_year = year
            }

            //creating one more method
            age() {
                let date = new Date()  //creating object of Date class
                this.age_val = date.getFullYear() this.purchase_year
                //console.log(this.age_val)
            }
            //creating another method
            display() {
                console.log(this.person + has a laptop of + this.make_co + make which uses + this.os + and is + this.age_val + year old)
            }
        }
        //create object of class laptop
        let sachin_laptop = new Laptop(Sachin, HP, Windows, 2011)
        let kohli_laptop = new Laptop(Kohli, Dell, Linux, 2019)
        let dhonin_laptop = new Laptop(Dhoni, Dell, Mac, 2022)
        console.log(kohli_laptop.os)
        kohli_laptop.age()
        console.log(Kohli’s laptop age in yrs is + kohli_laptop.age_val)
        sachin_laptop.age()
        sachin_laptop.display()
    </script>
</head>

<body>
    <H1> My Webpage</H1>
</body>

</html>
<html>

<head>
    <script>
        const sub1 = 80
        const sub2 = 80
        const sub3 = 80
        const sub4 = 0
        const sub5 = 0
        let sum = sub1 + sub2 + sub3 + sub4 + sub5
        let avg = sum / 5
        console.log(“Average marks scored by the student is “ + avg)
        //avg > 90 A, B..
        if (avg >= 90) {
            console.log(“Grade is A”)
        } else if (avg >= 80) {
            console.log(“Grade is B”)
        } else if (avg >= 70) {
            console.log(“Grade is C”)
        } else if (avg >= 60) {
            console.log(“Grade is D”)
        } else if (avg >= 50) {
            console.log(“Grade is E”)
        } else {
            console.log(“Grade is F”)
        }

        //Example 2
        let weight = 85  //kg
        let height = 1.4 //meters
        let bmi = weight / height ** 2
        console.log(“BMI is “ + bmi)

        //function to check if input number is prime or not
        function checkPrime(num) {
            let isPrime = true

            for (let i = 2; i < num / 2; i++) {
                if (num % i == 0) {
                    isPrime = false
                    break
                }
            }
            return isPrime
        }
        let result = checkPrime(61)
        if (result) {
            console.log(“Its a prime number”)
        } else {
            console.log(“Its not a prime number”)
        }
        st = 4500
        en = 5000
        console.log(“Now generating prime numbers between “ + st + ” and “ + en)
        for (i = st; i <= en; i++) {
            result = checkPrime(i)
            if (result) {
                console.log(i)
            }

        }
    </script>
</head>

<body>

</body>

</html>
<html>

<head>
    <script>
        class TipCalc {
            constructor(bill_amount) {
                this.amount = bill_amount
            }

            calculator() {
                let tip = –1
                // Bill amount is between 50 and 300 – then its 15%, otherwise its 20%
                if (this.amount >= 50 && this.amount <= 300) {
                    tip = this.amount * 0.15

                } else {
                    tip = this.amount * 0.20
                }
                return tip
            }
        }
        amount = 49
        let mytip1 = new TipCalc(amount)
        tip_cal = mytip1.calculator()
        total = amount + tip_cal
        console.log(“The bill was $” + amount + ” the tip was $” + tip_cal + ” total value is $” + total + “.”)

    </script>
</head>

<body>

</body>

</html>
<html>

<head>
    <script>
        let a = 11  //a to be less than 10 or throw error
        try {
            if (a > 15) throw “High value for a”
            if (a < 8) throw “Low value for a”
            let b = “hello”
            let c = 0
            c = b / g
            console.log(“Result = “, c)

        }
        catch (err) {
            console.log(“Caught an error in try. Error message: “ + err)
            let mesg = err
            if (err == “High value for a”) {
                alert(“Please reduce the value of a and try again”)
            }
            if (err == “ReferenceError: g is not defined”) {
                alert(“You are using g without declaring g variable”)
            }
        }
        finally {
            console.log(“I dont care about the error”)
        }
    </script>
</head>

<body>

</body>

</html>
// Try and catch to handle run time errors
<html>

<head>
    <script>
        today_date = new Date() //this will have date object storing current date and time
        console.log(today_date)

        today_date = new Date(2022, 10)  //year, month (previous)
        console.log(today_date)


        today_date = new Date(“October 1, 2020 05:36:12”)
        console.log(today_date)

        today_date = new Date(“2022-11-29”)
        console.log(today_date)

        today_date = new Date(2021, 11, 15, 1)  // year, month, date, hour
        console.log(today_date.getFullYear())
        console.log(today_date.getMonth())
        months_txt = [“January”, “February”, “March”, “April”, “May”,
            “June”, “July”, “August”, “September”, “October”, “November”, “December”]
        console.log(months_txt[today_date.getMonth() – 1])
        //getMinutes() getSeconds()  getMilliseconds() getDate()
        console.log(today_date.getDate())

        //Set the dates
        //setDate()  setFullYear() …
        console.log(today_date.setFullYear(2050))
        console.log(today_date.getDate())
        text = ‘{“player”: [{“Name”: “Sachin”, “City”: “Mumbai”,’ +
            ‘”Sports”: “Cricket”}, {“Name”: “Kapil”,’ +
            ‘”City”: “Gurgaon”,”Sports”: “Cricket”}]}’;
        json_val = JSON.parse(text)
        console.log(json_val.player[1].Name + ” : “ +
            json_val.player[0].City)
        /*
   today_date = new Date()
   console.log(today_date)

   today_date = new Date()
   console.log(today_date)

   today_date = new Date()
   console.log(today_date)

   today_date = new Date()
   console.log(today_date)

   today_date = new Date()
   console.log(today_date)
   */
    </script>
</head>

<body>

</body>

</html>
<html>

<head>

</head>

<body>
    <h1> Welcome </h1>
    <p id=“test1”> </p>
    <h2> How are you?</h2>
    <p id=“test2”> </p>
    <p id=“test3”> Twinkle Twinkle Little Star </p>
    <form name=“Form1” action=“practice7.html” method=“post”>
        Name: <input type=“text” name=“name”>
    </form>
    <script>
        choice = 5

        document.getElementById(“test1”).innerHTML = “<H3>Sachin<H3>”
        document.getElementById(“test1”).innerHTML = “Date: “ + Date()
        //id_test3 = document.getElementById(“test3”)
        document.getElementsByTagName
        val_test3 = document.getElementsByTagName(“p”)
        //console.log(val_test3)
        document.write(“THIS IS HELLO FROM ME”)
    </script>
</body>

</html>