—Albert Einstein—

"It has become appallingly obvious that our technology has exceeded our humanity."

—Steve Jobs—(Apple)

"A lot of companies have chosen to downsize, and maybe that was the right thing for them. We chose a different path. Our belief was that if we kept putting great products in front of customers, they would continue to open their wallets."

—Isaac Asimov—

"I do not fear computers. I fear lack of them."

—Rich Cook—

"Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning."

—Scott Cherf—

"To go faster, slow down. Everybody who knows about orbital mechanics understands that."

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:

Sunday, February 21, 2021

An Introduction of ES6+ JavaScript

Summary:👉 TABLE OF CONTENTS:

  • Chapter 1: WHAT IS A JAVASCRIPT FRAMEWORK?
  • Chapter 2: A DEFINITION OF VANILLA JAVASCRIPT.
  • Chapter 3: A DEFINITION JAVASCRIPT LIBRARIES.
  • Chapter 4: THE PURPOSE OF JAVASCRIPT

APPLICATION FRAMEWORK MEAN?

In this chapter, we've discussed application frameworks and their role in modern embedded systems development.
An application framework may be a software library that gives a fundamental structure to support the event of applications for a selected environment. An application framework acts because of the skeletal support to create an application.

WHAT IS A JAVASCRIPT FRAMEWORK?

Think of building websites and web apps like building a house. once you began to create a house, you'll create all of your own building materials from scratch and begin building with no schematics, but that approach would be incredibly time-consuming and doesn’t make tons of sense. It’s more likely that you simply would purchase pre-manufactured building materials. then assemble them supported a blueprint to suit your specific needs.

Coding is extremely similar. once you began to code an internet siteyou'll code every aspect of that site from scratch, but there are certain common website features that make more sense to use from a template if you would like a wheel, as an example, it’s tons more sense to shop for one than it's to reinvent it. And that’s where JavaScript frameworks inherit play

"At their most basic, JS frameworks are collections of JavaScript code libraries (see below) that provide developers with pre-written JS code to use for routine programming features and tasks-literally, a framework to build websites or web applications around."

JavaScript runtime built on Chrome’s V8 JavaScript engine”, which it “uses an event-driven, non-blocking I/O model that creates it lightweight and efficient”. except for some, that's not the best of explanations.

Some examples of JavaScript Frameworks:

  • Angular
  • Ember JS
  • Next JS

A DEFINITION OF VANILLA JAVASCRIPT:


"VanillaJS is a name to refer to using plain JavaScript without any additional libraries like jQuery. People use it as a joke to remind other developers that many things can be done nowadays without the need for additional JavaScript libraries."

Using the JavaScript language alone means you’d need to rewrite the code for these functions whenever they occur. JS frameworks and libraries give developers the flexibility to use prewritten code for common JavaScript functions and to make their own functions which will then be reused as needed. 

A DEFINITION JAVASCRIPT LIBRARIES: 


JavaScript library may be a library of pre-written JavaScript that permits for easier development of JavaScript-based applications, especially for AJAX and other web-centric technologies.
Some JavaScript libraries allow for easier integration of JavaScript with other web development technologies, Like CSSPHPRuby, and Java. Many libraries include code to detect differences between runtime environments and take away the necessity for applications to permit such inconsistencies.

Examples of JavaScript Libraries:

  • JQuery
  • Node JS
  • React JS

THE PURPOSE OF JAVASCRIPT

  • Very easy to implement
  • Works on web users’ computers
  • Can help fix browser problems or patch holes in browser support.
  • Can load content into the document if and when the user needs it, without reloading the whole page
  • Can test for what's possible in your browser and react accordingly


👋So, I hope you can get an idea about JS. Then we talk coding part about the JAVASCRIPT in the next article. And also, in the next article, I will give a summary of codes.



Share:

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