KANNIKA LIBRETA
  • Home
  • Kotlin & Spring Boot

~

Intro

Picture
  • Worlds's most popular programming language​
  • -
  • Old JavaScript examples may use a type attribute: <script type="text/javascript"> But the type attribute is not required, JavaScript is the default scripting language in HTML

  • Placing scripts at the bottom of the <body> element improves the display speed, because script interpretation slows down the display.

  • A computer program is a list of "instructions" to be "executed" by a computer.
  • In a programming language, these programming instructions are called statements.
  • A JavaScript program is a list of programming statements.

  • On the web, you might see examples without semicolons.
  • Ending statements with semicolon is not required, but highly recommended.

  • //JavaScript Code can written in Broken lines like below:
  • document.getElementById("demo").innerHTML =
  • "Hello Kankan!";
  • // If a JavaScript statement does not fit on one line, the best place to break it is after an operator

Basics

Basics
Variables
A JavaScript variable name must begin with:
  • A letter (A-Z or a-z)
  • A dollar sign ($)
  • Or an underscore (_)

4 Ways to Declare a JavaScript Variable:
  • Using var
  • Using let
  • Using const
  • Using nothing

*Note: Variables created without a declaration keyword (var, let, or const) are always global, even if they are created inside a function. Global variables live until the page is discarded, like when you navigate to another page or close the window.

Let
Variables defined with let cannot be Redeclared, must be Declared before use, and have Block Scope
  • let x = "Kannika";
  • let x = 0;    // SyntaxError: 'x' has already been declared

  • var y = "Kannika";
  • var y = 0;    // Allowed to be redeclared when using var

  • {    // This is called a block
  •   let x = 2;
  • }
  • // x can NOT be used here

JavaScript Let Hoisting
  • // Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope
  • carName = "Lambo";
  • var carName;
var x = 10;
// Here x is 10
{
var x = 2;
// Here x is 2
}
// Here x is 2
let x = 10;
// Here x is 10
{
let x = 2;
// Here x is 2
}
// Here x is 10
var x = 2;   // Allowed
let x = 3;   // Not allowed
{
let x = 2;   // Allowed
let x = 3;   // Not allowed
}
{
let x = 2;   // Allowed
var x = 3;   // Not allowed
}
Const
Variables defined with const cannot be Redeclared and cannot be Reassigned but must have have Block Scope.
Always declare a variable with const when you know that the value should not be changed.
Declaring a variable with const is similar to let when it comes to Block Scope. Below are some rules.
  • you can NOT:
    • Reassign a constant value
    • Reassign a constant array
    • Reassign a constant object
  • But you CAN:
    • Change the elements of constant array
    • Change the properties of constant object

  • const PI = 3.141592653589793;
  • PI = 3.14;      // This will give an error
  • const PI;     // Error: const variable must be assigned
  • PI = 3.14159265359;




  • const cars = ["Lambo", "Ferarri", "McLaren"];    // You can create a constant array
  • cars[0] = "Chevorlet";    // You can change an element
  • cars.push("Audi");    // You can add an element
  • cars = ["Benz", "BMW", "Porsche"];    // ERROR

  • const car = {type:"McLaren", model:"650", color:"white"};    // You can create a const object
  • car.color = "blue";    // You can change a property
  • car.owner = "Kannika";    // You can add a property
  • car = {type:"Ford", model:"GT", color:"red"};    // ERROR
Operators
**     -
    Exponentiation (same as Math.pow(x, y)
typeof 
    -     Returns the type of a variable
instanceof
    -     Returns true if an object is an instance of an object type
===
    -     equal value and equal type
!==
    -     not equal value or not equal type
>>>     -     unsigned right shift (ex: 5>>>1 = 0101>>>1 = 0010 = 2)
​
  • /* If you put a number in quotes, the rest of the numbers will be treated as strings, and concatenated. */
  • let x = 4 + 3 + "5";
  • console.log(x)   // x = (4+3) + "5" = 7+"5" = 75
​
BE(D/M)(A/S) is followed even in JavaScript
Data Types
Javascript are always one type: double (64-bit floating point)

JavaScript has 8 Datatypes
  • 1. String
  • 2. Number
  • 3. Bigint (ex: let x = BigInt("123456789012345678901234567890");)
  • 4. Boolean
  • 5. Undefined
  • 6. Null
  • 7. Symbol
  • 8. Object

The object data type can contain:
  • 1. An object
  • 2. An array
  • 3. A date
  • ex: JavaScript objects are written with curly braces {}
  • const person = {firstName:"Kannika", lastName:"Kabilar", age:23, eyeColor:"black"};

Functions

Functions
Functions
  • function toCelsius(fahrenheit) {
  •   return (5/9) * (fahrenheit-32);
  • }
  • console.log("The temperature is " + toCelsius(32) + " Celsius");    // 0 degree celsius

Anonymous Function (a function without a name)
  • const x = function (a, b) {return a * b};
  • let z = x(4, 3);
  • // Anonymous Self-Invoking Function
  • (function () {
  •   let x = "Hello!!";  // I will invoke myself
  • })();

JavaScript Function() Constructor
  • const myFunction = new Function("a", "b", "return a * b");
  • let x = myFunction(4, 5);

Function Hoisting
Because of hoisting, JavaScript functions can be called before they are declared. But Functions defined using an expression are not hoisted.
  • myFunction(5);
  • function myFunction(y) {
  •   return y * y;
  • }

Arrow Functions
  • const x = (x, y) => { return x * y };    // Cannot be hoisted - works best for 1 line functions

Default Parameter Value
  • function myFunction(x, y = 10) {    // If value of y is not passed, it'll equal 10
  •   return x + y;
  • }
  • myFunction(5);

Call & Apply Method
It can be used to invoke (call) a method with an owner object as an argument (parameter). With call(), an object can use a method belonging to another object.​
  • const person = {
  •   fullName: function(city, country) {
  •     return this.firstName + " " + this.lastName + "," + city + "," + country;
  •   }
  • }
  • const person1 = {
  •   firstName:"Kannika",
  •   lastName: "Kabilar"
  • }
  • person.fullName.call(person1, "Toronto", "Canada");
  • // Same as call() but => The apply() method is very handy if you want to use an array instead of an argument list
  • person.fullName.apply(person1, ["Toronto", "Canada"]);   

JavaScript Closure
A closure is a function having access to the parent scope, even after the parent function has closed.
  • const add = (function () {
  •   let counter = 0;
  •   return function () {counter += 1; return counter}
  • })();

  • add();
  • add();
  • add();

  • // the counter is now 3
Arguments are Passed by Value
If a function changes an argument's value, it does not change the parameter's original value.
Changes to arguments are not visible (reflected) outside the function.

Objects are Passed by Reference
If a function changes an object property, it changes the original value.
Changes to object properties are visible (reflected) outside the function.

*Note: Comparing two JavaScript objects always returns false.

Objects

Objects
Objects are variables too. But objects can contain many values. A method is a function stored as a property (attribute).

  • // Ex: (standard)
  • const person = {
      firstName: "Kannika",
      lastName : "Kabilar",
      id       : 1999,
      fullName : function() {
        return this.firstName + " " + this.lastName;
      }
    };
  • // Ex: (using new Object())
  • const person = new Object();
    person.firstName = "Kannika";
    person.lastName = "Kabilar";
    person.id = 50;
    person.eyeColor = "black";

​Booleans, Numbers, and Strings can be objects if defined with the new keyword.

Immutable: 
Primitive values are immutable (they are hardcoded and cannot be changed).
if x = 3.14, you can change the value of x, but you cannot change the value of 3.14.

Properties
Accessing Properties
  • objectName.property      // person.age
  • objectName["property"]   // person["age"]
  • objectName[expression]   // x = "age"; person[x]

Looping Through Properties of an Object
  • const person = {
  •   fname: "Kannika",
  •   lname: "Kabilar",
  •   age: 23
  •   cars: {
  •     car1:"McLaren",
  •     car2:"BMW",
  •     car3:"Lambo"
  •   }
  • };
  • for (let x in person) {
  •   txt += person[x];
  • }

  • person.nationality = "Canadian";    // new properties can easily be added like this
  • delete person.age;    // deletes properties of an object

Accessing nested objects
  • myObj.cars.car2;
  • myObj["cars"]["car2"];

Methods
Accessing Methods
  • name = person.fullName();    
  • name = person.fullName;    // If you access the fullName property, without (), it will return the function definition

Adding a Method
  • person.name = function () {
  •   return this.firstName + " " + this.lastName;
  • };

Displaying Objects - Using JSON Stringify
  • const person = {
  •   name: "Kannika",
  •   age: 23,
  •   city: "Toronto"
  • };

  • let myString = JSON.stringify(person);
  • document.getElementById("demo").innerHTML = myString;   
  • // The result will be a string following the JSON notation: {"name":"Kannika", "age":23, "city":"Toronto"}

Accessors
- Provides simpler syntax
  • const person = {
  •   firstName: "Kannika",
  •   lastName: "Kabilar",
  •   get fullName() {
  •     return this.firstName + " " + this.lastName;
  •   }  language: "",
  •   set lang(lang) {
  •     this.language = lang;
  •   }
  • };

  • // Display data from the object using a getter:
  • document.getElementById("demo1").innerHTML = person.fullName;

  • // Set an object property using a setter:
  • person.lang = "en";

  • // Display data from the object:
  • document.getElementById("demo2").innerHTML = person.language;

Constructors
*Note: It is considered good practice to name constructor functions with an upper-case first letter.
  • function Person(firstName, lastName, age, eyeColor) {
  •   this.firstName = firstName; 
  •   this.lastName = lastName;
  •   this.age = age;
  •   this.eyeColor = eyeColor;
  •   this.changeName = function (name) {
  •     this.lastName = name;
  •   };
  • }

  • const fighter1 = new Person("Nina", "Williams", 24, "blue");
  • const fighter2 = new Person("Jin", "Kazama", 21, "grey");

JavaScript has object versions of the primitive data types String, Number, and Boolean. But there is no reason to create complex objects. Primitive values are much faster
  • Use string literals "" instead of new String().
  • Use number literals 50 instead of new Number().
  • Use boolean literals true / false instead of new Boolean().
  • Use object literals {} instead of new Object().
  • Use array literals [] instead of new Array().
  • Use pattern literals /()/ instead of new RegExp().
  • Use function expressions () {} instead of new Function()

Prototype Property
Sometimes you want to add new properties (or methods) to an object constructor OR to all existing objects of a given type.
The JavaScript prototype property allows you to add new properties to object constructors
  • function Person(first, last, age, eyecolor) {
  •   this.firstName = first;
  •   this.lastName = last;
  •   this.age = age;
  •   this.eyeColor = eyecolor;
  • }

  • Person.prototype.nationality = "English";
  • Person.prototype.name = function() {
  •   return this.firstName + " " + this.lastName;
  • };

Iterables
Iterable objects are objects that can be iterated over with for..of. Technically, iterables must implement the Symbol.iterator method. The iterator protocol defines how to produce a sequence of values from an object. An object becomes an iterator when it implements a next() method.
The next() method must return an object with two properties:
  • value (the next value)
  • done (true or false)

  • // Create an Object
  • myNumbers = {};

  • // Make it Iterable
  • myNumbers[Symbol.iterator] = function() {
  •   let n = 0;
  •   done = false;
  •   return {
  •     next() {
  •       n += 10;
  •       if (n == 100) {done = true}
  •       return {value:n, done:done};
  •     }
  •   };
  • }
  • // Now you can use for .. of ..
  • for (const num of myNumbers) {
  •   // Any Code Here
  • }

Sets
A JavaScript Set is a collection of unique values. Each value can only occur once in a Set. A Set can hold any value of any data type.
  • // Create a Set
  • const letters = new Set(["a","b","c"]);

  • // Add Values to the Set
  • letters.add("d");
  • letters.add("e");

  • // List all entries
  • let text = "";
  • letters.forEach (function(value) {
  •   text += value;
  • })

  • // Create an Iterator
  • const myIterator = letters.values();

  • // List all Values
  • let text = "";
  • for (const entry of myIterator) {
  •   text += entry;
  • }

Maps
A Map holds key-value pairs where the keys can be any datatype. A Map remembers the original insertion order of the keys.
  • // Create a Map - 1
  • const fruits = new Map([
  •   ["apples", 500],
  •   ["bananas", 300],
  •   ["oranges", 200]
  • ]);

  • // Create a Map - 2
  • const fruits = new Map();
  • // Set Map Values
  • fruits.set("apples", 500);    // The set() method can also be used to change existing Map values
  • fruits.set("bananas", 300);    // Objects can also be used as keys instead of strings
  • fruits.set("oranges", 200);

  • fruits.get("apples");    // Returns 500
  • fruits.size;    // Returns 3
  • fruits.delete("bananas");
  • fruits.has("apples");    // True
  • fruits.has("bananas");    // False
  • typeof fruits;    // Returns object
  • fruits instanceof Map;    // Returns true

  • // List all entries - 1
  • let text = "";
  • fruits.forEach (function(value, key) {
  •   text += key + ' = ' + value;
  • })

  • // List all entries - 2
  • let text = "";
  • for (const x of fruits.entries()) {    // fruits.keys(), fruits.values()
  •   text += x;
  •   text += " ";
  • }    // text = "apples,500 bananas,300 oranges,200"
HTML DOM chapter teaches about events and event handlers.

Strings

STRINGS
You can use quotes inside a string, as long as they don't match the quotes surrounding the string but you can also use backslash to include apostophes.

  • let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  • let length = text.length;    // length = 26

3 ways to get parts of a string
  • slice(start, end)
  • substring(start, end)
  • substr(start, length)

  • // Ex: (using negative indices)
  • let text = "Apple, Banana, Kiwi";
  • let part1 = text.slice(-3);    // part = "iwi"
  • let part2 = text.slice(-12, -6);    // part = "Banana"

  • let text = "Please visit Canada!";
  • let newText = text.replace("Canada", "USA");   
  • // replace() returns a new string, does not change og string and only replaces first occurrence
  • // regex can be used in the first param

  • // Converting string to arrays
  • text.split(",")    // Split on commas

JavaScript Search Methods
  • String indexOf()
  • String lastIndexOf()
  • String search()
  • String match()
  • String matchAll()
  • String includes()
  • String startsWith()
  • String endsWith()

Template Literals
  • let firstName = "Kannika";
  • let lastName = "Kabilar";
  • let text = `Welcome ${firstName}, ${lastName}!`;

Numbers

Numbers and bigint
JavaScript has only one type of number. Numbers can be written with or without decimals.
Scientific Notation
  • let x = 123e5;    // 12300000
  • let y = 123e-5;   // 0.00123

Precision = 15 bits
  • let x = 999999999999999;   // x will be 999999999999999
  • let y = 9999999999999999;  // y will be 10000000000000000

JavaScript will try to convert strings to numbers in all numeric operations (except for +)
  • let x = "100";
  • let y = "10";
  • let z = x / y;    // z = 10

  • let x = 100 / "Apple";    // x = NaN
  • isNaN(x);    // True

Infinity
  • let myNumber = 2;
  • // Execute until Infinity
  • while (myNumber != Infinity) {
  •   myNumber = myNumber * myNumber;
  • }

Hexadecimal
  • let x = 0xFF;

BigInt
To create a BigInt, append n to the end of an integer or call BigInt(). Operators that can be used on a JavaScript Number can also be used on a BigInt.
*Note:
Arithmetic between a BigInt and a Number is not allowed (type conversion lose information).
Unsigned right shift (>>>) can not be done on a BigInt (it does not have a fixed width).
  • let x = 1234567890123456789012345n;
  • let y = BigInt(1234567890123456789012345)

  • let hex = 0x20000000000003n;
  • let oct = 0o400000000000000003n
  • let bin = 0b100000000000000000000000000000000000000000000000000011n;

Arrays

Arrays
It is a common practice to declare arrays with the const keyword

  • const planets = ["Mercury", "Venus", "Neptune"];
  • planets[0] = "Earth";
  • planets.length   // Returns # of elements = 3
  • planets.sort()   // Sorts the array
  • planets.push("Mars");  // Adds a new element (Mars) to planets
  • planets[6] = "Jupiter";  // Creates undefined "holes" in planets

  • let type = typeof planets;    // type = object
  • Array.isArray(planets);
  • planets instanceof Array;

Looping Through Array Elements
  • const fruits = ["Banana", "Orange", "Apple", "Mango"];
  • let fLen = fruits.length;

  • let text = "<ul>";
  • for (let i = 0; i < fLen; i++) {
  •   text += "<li>" + fruits[i] + "</li>";
  • }
  • text += "</ul>";

*Note:
  • In JavaScript, arrays use numbered indexes.  
  • In JavaScript, objects use named indexes.

Array Methods
  • const fruits = ["Banana", "Orange", "Apple", "Mango"];

  • document.getElementById("demo").innerHTML = fruits.toString();
  • // result:  Banana,Orange,Apple,Mango

  • document.getElementById("demo").innerHTML = fruits.join(" * ");
  • // result:  Banana * Orange * Apple * Mango

  • let fruit = fruits.pop();    // removes and returns the last element | fruit = Mango
  • let fruit = fruits.shift();    // removes and returns the first element | fruit = Banana
  • fruits.unshift("Lemon");    // adds new element to the beginning of the array and returns array length
  • delete fruits[2];    // delete element at given index

Merging (Concatenating) Arrays
The concat() method does not change the existing arrays. It always returns a new array.
  • const arr1 = ["Nina", "Anna"];
  • const arr2 = ["Jin", "Kazuya", "Jun"];
  • const arr3 = ["Lars", "Alisa"];
  • const fighters = arr1.concat(arr2, arr3);    // can take-in any number of args
  • const fighters = arr1.concat("Steve");     // can also merge with values

Splice
The first parameter (2) defines the position where new elements should be added (spliced in).
The second parameter (2) defines how many elements should be removed.
The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added
  • // Ex:
  • const fruits = ["Banana", "Orange", "Apple", "Mango"];
  • let removed = fruits.splice(2, 2, "Lemon", "Kiwi");    // modifies original array and returns removed elements

Slice
The slice() method creates a new array and does not remove any elements from the source array.
  • const fruits = ["Apple", "Banana", "Mango", "Orange", "Lemon"];
  • const citrus = fruits.slice(3);    // citrus = "Orange", "Lemon"
  • const yellow = fruits.slice(1, 3);    // yellow = "Banana", "Mango"

Sort
By default, the sort() function sorts values as strings. - to sort numbers provide a function
  • const points = [40, 100, 1, 5, 25, 10];
  • points.sort(function(a, b){return a - b});

Sorting Objects
  • const cars = [
  •   {type:"Lambo", year:2017},
  •   {type:"Ford", year:2001},
  •   {type:"BMW", year:2010}
  • ];
  • cars.sort(function(a, b){return a.year - b.year});

Highes element of an array
  • function myArrayMax(arr) {
  •   return Math.max.apply(null, arr);
  • }

Filtering
  • const numbers = [45, 4, 9, 16, 25];
  • const over18 = numbers.filter(myFunction);
  • function myFunction(value, index, array) {
  •   return value > 18;
  • }

Includes
  • const fruits = ["Banana", "Orange", "Apple", "Mango"];
  • fruits.includes("Mango"); // is true
JavaScript can handle date many different formats

Math, If .. else if .. else, switch, For loop, While loop

Math, If .. else if .. else, switch, For loop, While loop
  • // Math.trunc(x) returns the integer part of x
  • Math.trunc(4.9);    // returns 4


  • // Returns a random integer from 0 to 9:
  • Math.floor(Math.random() * 10);

  • // If .. else if .. else example
  • if (time < 10) {
  •   greeting = "Good morning";
  • } else if (time < 20) {
  •   greeting = "Good day";
  • } else {
  •   greeting = "Good evening";
  • }

  • // Switch example
  • ​switch (new Date().getDay()) {
  •   case 6:
  •     text = "Today is Saturday";
  •     break;
  •   case 0:
  •     text = "Today is Sunday";
  •     break;
  •   default:    // If today is neither Saturday (6) nor Sunday (0), write a default message
  •     text = "Looking forward to the Weekend";
  • }


  • // For loop example
  • for (let i = 0, len = cars.length, text = ""; i < len; i++) {
  •   text += cars[i] + "<br>";
  • }​
  • // For .. in .. example
  • const person = {fname:"Kannika", lname:"Kabilar", age:23};
  • let text = "";
  • for (let x in person) {
  •   text += person[x];
  • }
  • const numbers = [45, 4, 9, 16, 25];
  • let txt = "";
  • for (let x in numbers) {
  •   txt += numbers[x];
  • }

  • // For .. of .. example
  • const cars = ["BMW", "Lambo", "McLaren"];
  • let text = "";
  • for (let x of cars) {
  •   text += x;
  • }

  • ​// While loop example
  • const cars = ["BMW", "Lambo", "McLaren", "Ford"];
  • let i = 0;
  • let text = "";
  • while (cars[i]) {
  •   text += cars[i];
  •   i++;
  • }

Maps, Regex, Strict Mode

Maps
// Create a Map
const fruits = new Map();

// Set Map Values
fruits.set("apples", 500);
fruits.set("bananas", 300);
fruits.set("oranges", 200);
​
// The set() method can also be used to change existing Map values
fruits.set("apples", 400);
fruits.get("apples");    // Returns 400
​fruits.has("apples");    // Returns True
Regex
let text = "Visit KannikaLibreta!";
let n = text.search("KannikaLibreta");    // n = 6
let n = text.search(/kannikalibreta/i);     // same as above but performs a case insensitive search
​
let text = "Visit Canada!";
let result = text.replace(/canada/i, "USA");    // result = "Visit USA!"
Strict Mode
Strict Mode
It helps you to write cleaner code, like preventing you from using undeclared variables.
The "use strict" directive is only recognized at the beginning of a script or a function.

x = 3.14;       // This will not cause an error
myFunction();

function myFunction() {
  "use strict";
  y = 3.14;   // This will cause an error
}
"use strict";
let x = 3.14;
delete x;    // This will cause an error because deleting is not allowed

​Along with many more rules ...

Modules, Debugging

Modules
  • <script type="module">
  • import message from "./message.js";
  • </script>

Named Exports
  • export const name = "Kazuya";
  • export const age = 48;
  • Importing Named Exports
  • import { name, age } from "./person.js";

Default Exports
  • const name = "Jesse";
  • const age = 40;
  • export {name, age};
  • Importing Default Exports
  • import message from "./message.js";
Debugging
Debugging
Often, when programming code contains errors, nothing will happen. There are no error messages, and you will get no indications where to search for errors. Searching for (and fixing) errors in programming code is called code debugging.
​
  • Primary Debugger: use console.log()

The debugger keyword stops the execution of JavaScript, and calls (if available) the debugging function.
With the debugger turned on, this code will stop executing before it executes the third line.
  • let x = 15 * 5;
  • debugger;
  • document.getElementById("demo").innerHTML = x;
Create a free web site with Weebly
  • Home
  • Kotlin & Spring Boot