Wednesday, February 24, 2021

Learn JAVASCRIPT with codes

 Summary:👉 TABLE OF CONTENTS:

  • Chapter 01: Variables
  • Chapter 02: Operators
  • Chapter 03: Data Types
  • Chapter 04: Functions
  • Chapter 05: Global Functions
  • Chapter 06: Loops
  • Chapter 07: If- else
  • Chapter 08: Switch Statement
  • Chapter 09: Arrays
  • Chapter 10: JSON j
  • Chapter 11: Promises
  • Chapter 12: Helpful Codes


JavaScript is a programming language that powers the dynamic behavior on most websites. In this article, we are focusing on the basic JAVASCRIPT code patterns. So, JAVASCRIPT is most suitable for beginner developers who have basic experience in any programming language.

INTRODUCTION TO BASIC 

Variables
  • Variables are containers for storing data values.
  •  Uses reserved keyword var to declare a variable.
        var a;                          // variable
        var b = "hello";                // string
        var c = "Hi" + " " + "Danu";    // = "Hi Danu"
        var d = 2 + 2 + "3";            // = "43"
        var e = [4679];           // array
        var f = true;                   // boolean
        var g = function () { };        // function object
        var a = 5b = 2c = a + b;    // one line
        const PI = 3.14;                // constant
        let z = 'xxx';                  // block scope local variable

Operators 
  • Performs some operations on single or multiple operands(data value) and produces a result.
  • JavaScript supports the following types of operators.
      • Arithmetic Operators
      • Logical Operators
      • Comparison Operators
      • Conditional Operators
      • Assignment Operators
        a = b + c - d;      // addition, substraction
        a = b * (c / d);    // multiplication, division
        x = 100 % 48;       // modulo. 100 / 48 remainder = 4
        a++; b--;           // postfix increment and decrement

        a * (b + c)         // grouping
        person.age          // member
        person[age]         // member
        !(a == b)           // logical not
        a != b              // not equal
        typeof a            // type (number, object, function...)
        x << 2x >> 3      // minary shifting
        a = b               // assignment
        a == b              // equals
        a === b             // strict equal
        a != b              // unequal
        a !== b             // strict unequal

        a < ba > b        // less and greater than
        a <= ba >= b      // less or equal, greater or eq
        a += b              // a = a + b (works with - * %...)
        a && b              // logical and
        a || b              // logical or

Data Types 
  • There are two types of Data Types.
      • Primitive Data Type
          • String
          • Boolean
          • Number
          • Null
          • Undefined
      • Non-primitive Data Type
          • Array
          • Object
          • Date
        var age = 18;                                   // number 
        var name = "Tom";                               // string
        var fullName = { first: "Tom"last: "Doe" };   // object
        var truth = true;                               // boolean
        var sheets = ["HTML""CSS""JS"];             // array
        var atypeof a;                                // undefined
        var x = null;                                   // value null

Functions 
  • JavaScript function can be defined using the function keyword.
        function addNumbers(ab) {
            return a + b;;
        }
        x = addNumbers(12);


Global Functions 

        eval();                     // executes a string as if it was script code
        String(10);                 // return string from number
        (10).toString();            // return string from number
        Number("10");               // return number from string
        encodeURI(uri);             // encode URI. Result: "my%page.asp"
        decodeURI(enc);             // decode URI. Result: "my page.asp"
        encodeURIComponent(uri);    // encode a URI component
        decodeURIComponent(enc);    // decode a URI component
        isFinite();                 // is variable a finite, legal number
        isNaN();                    // is variable an illegal number
        parseInt();                 // parses a string and returns an integer
        parseFloat();               // returns floating point number of string

Loops 

    ✔ For Loop
    • For loop requires the following 3 parts.
      • Initializer - Initialize our counter to a starting value
      • condition - Specify a condition that must evaluate to true for the next iteration
      • Iteration -  increase or decrease the counter                                                       
        for (var i = 0i < 10i++) {
            document.write(i + ": " + i * 3 + "<br />");
        }
        var sum = 0;
        for (var i = 0i < a.lengthi++) {
            sum += a[i];
        }
        html = "";
        for (var i of custOrder) {
            html += "<li>" + i + "</li>";
        }

    
    ✔ While Loop
    • Only requires condition expression.
    • The purpose of a while loop is to execute a statement or code block repeatedly as long as an expression is true.  
        
        var i = 1;                      // initialize
        while (i < 100) {               // enters the cycle if statement is true
            i *= 2;                     // increment to avoid infinite loop
            document.write(i + ", ");   // output
        }

        ////----Do-while Loop----////
        var i = 1;                      // initialize
        do {                            // enters cycle at least once
            i *= 2;                     // increment to avoid infinite loop
            document.write(i + ", ");   // output
        } while (i < 100)               // repeats cycle if statement is true at the end


    ✔ Break & Continue
    • Break statement "jumps out" of a loop.
    • Continue statement "jumps over" one iteration in the loop.

        ////----Break----////
        for (var i = 0i < 10i++) {
            if (i == 5) {
                break;                      // stops and exits the cycle
            }
            document.write(i + ", ");       // last output number is 4
        }

        ////----Continue----////
        for (var i = 0i < 10i++) {
            if (i == 5) {
                continue;                   // skips the rest of the cycle
            }
            document.write(i + ", ");       // skips 5
        }


If - else 
  • The 'If - else' statement is the next form of control statement that allows JavaScript to execute statements in a more controlled way.

        if ((age >= 16) && (age < 19)) {        // logical condition
            status = "Eligible.";               // executed if condition is true
        } else {                                // else block is optional
            status = "Not eligible.";           // executed if condition is false
        }


Switch Statement 
  • The switch statement is useful when we want to execute one of the multiple code blocks based on the return value of a specified expression.

    switch (new Date().getDay()) {      // input is current day
    case 1:                         // if (day == 1)
        text = "Monday";          
        break;
    case 0:                         // if (day == 0)
        text = "Sunday";
        break;
    default:                        // else...
        text = "Something";
    } 
  

Arrays 
  • An array in JavaScript can be defined and initialized in two ways, Array literal and Array constructor syntax.
        ✔ Array Literal
      • It takes a list of values separated by a comma and enclosed in square brackets.
        
        var stringArray = ["one""two""three"];
        var numericArray = [1234];
        var decimalArray = [1.11.21.3];

        
        ✔ Array Constructor
      • Initialize an array with Array constructor syntax using a new keyword.

        var stringArray = new Array();
        stringArray[0] = "one";
        stringArray[1] = "two";

        var numericArray = new Array(3);
        numericArray[0] = 1;
        numericArray[1] = 2;


JSON j 
  • JSON - JavaScript Object Notation
  • JSON is a syntax for storing and exchanging data.
  • JSON is a text format that is completely language-independent.

        var str = '{"names":[' +                    // crate JSON object
            '{"first":"Don","lastN":"Jon" },' +
            '{"first":"John","lastN":"Lewis" },' +
            '{"first":"King","last":"Jordan" }]}';
        obj = JSON.parse(str);                      // parse
        document.write(obj.names[1].first);         // access

        ////----Sending Data----////
        var myObj = { "name": "Danuka""age": 23"city": "Sri Lanka" };  // create object
        var myJSON = JSON.stringify(myObj);                                // stringify
        window.location = "demo.php?x=" + myJSON;                          // send to php

        ////----Storing Data and retrieving Data----////
        myObj = { "name": "Danuka""age": 23"city": "Sri Lanka" };
        myJSON = JSON.stringify(myObj);                 // storing data
        localStorage.setItem("testJSON"myJSON);
        text = localStorage.getItem("testJSON");        // retrieving data 
        obj = JSON.parse(text);
        document.write(obj.name);


Promises 
  • Contains both the producing code and calls to the consuming code.
  • A Promise may be a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason.
  • A Promise Object can be :
    • Pending:: Result - Undefined
    • Fulfilled:: Result - a result value
    • Rejected:: Result - an error object

        function sum(xy) {
            return Promise(function (resolvereject) {                               
                setTimeout(function () {                                     // send the response after 1 second
                    if (typeof x !== "number" || typeof y !== "number") {    // testing input types
                        return reject(new TypeError("must to be numbers"));
                    }
                    resolve(x + y);
                }, 3000);
            });
        }
        var myPromise = sum(55);
        myPromise.then(function (result) {
            document.write(" 5 + 5: "result);
            return sum(null"num");              // Invalid data and return another promise
        }).then(function () {                     // Won't be called because of the error
        }).catch(function (err) {                 // The catch handler is called instead, after another second
            console.error(err);                   // => Please provide two numbers to sum.
        });


✅ Now I think you are got an idea about JavaSCript coding. So, we will see in the next article.✋✋


👉👉Helpful Codes👇👇 

✔outputs


        console.log(x);             // write to the browser console
        document.write(x);          // write to the HTML
        alert(x);                   // output in an alert box
        confirm("Hello");           // yes/no dialog, returns true/false depending on user click
        prompt("Your age?""0");   // input dialog. Second argument is the initial value


✔Objects

        var student = {                 // object name
            firstName: "Danuka",        // list of properties and values
            lastName: "Dilshan",
            age: 23,
            height: 185,
            fullName: function () {     // object function
                return this.firstName + " " + this.lastName;
            }
        };
        student.age = 25;           // setting value
        student[age]++;             // incrementing
        name = student.fullName();  // call object function


✔Methods


        x.toString();                        // convert to string: results "Bulldog,Beagle,Labrador"
        x.join(" * ");                       // join: "Bulldog * Beagle * Labrador"
        x.pop();                             // remove last element
        x.push("Something");                 // add new element to the end
        x[x.length] = "Something";           // the same as push
        x.shift();                           // remove first element
        x.unshift("Something");              // add new element to the beginning
        delete x[0];                         // change element to undefined (not recommended)
        x.splice(20"y""z");            // add elements (where, how many to remove, element list)
        var animals = x.concat(catsbirds); // join two arrays (dogs followed by cats and birds)
        x.slice(14);                       // elements from [1] to [4-1]
        x.sort();                            // sort string alphabetically
        x.reverse();                         // sort string in descending order
        x.sort(function (ab) { return a - b });   // numeric sort
        x.sort(function (ab) { return b - a });   // numeric descending sort
        highest = x[0];                         // first item in sorted array is the lowest (or highest) value
        x.sort(function (ab) { return 0.5 - Math.random() });     // random order sort






Share:

1 comment:

About Me

My photo
As a programmer, work in a constantly evolving environment. I'll create, maintain, audit, and improve systems to fulfill particular needs, often as advised by an analyst or architect, testing both hard and software systems to diagnose and resolve system faults. And also I am a creative thinker and self-learner, adept in web & mobile application development.

What is CLOUD COMPUTING

Search This Blog

Blog Archive