Javascript essentials on Udemy

Notes from Javascript essentials course on Udemy from Lawrence Turton.

1 - Intro

  • nothing

2 - History

  • 1995, created in 10 days, it was called Mocha
  • It was called Livescript, renamed to JavaScript (as a joke)
  • Microsoft “invented” Jscript
  • ECMAscript takes care of standards

3 - How JS works

  • browser (client side)
    • Rendering Engine
      • DOM parser
      • CSS parser
    • Javascript Engine (Chrome V8 Engine, Safari Nitro…)
      • JIT Compilers (just in time) - compiles source into machine code

4 - JS console

5 - What is an object

  • programming consists only from nouns, adjectives and verbs
  • nouns, adjectives and nouns are properties apple = { width: 25, color: “red”, eat: function() {“Eat the apple.”;} }
  • verbs - performing action, function
  • method - a function that is contained within an object
  • you can understand and practice objects in real life (think of an object with stuff around you - fridge, computer…)
  • objects can contain other objects
Nested object
Nested object
  • Encapsulation - grouping data together

6 - JS syntax

  • API - application Programming Interface, collection of functions
  • jQuery is extended API - needs JS, then build its own API

7 - Primitive data

  • strings - defined with quotes
  • escape characters - backslash \
  • integers - whole numbers
  • floating numbers - frictional numbers
  • boolean - true/false
  • null - empty, void.
  • undefined - empty, void, too.
  • NaN - not a number

8 - Variables, constants & assignment

  • variables
    • don’t start with capital letter (?), number (not allowed), special char
    • you can create blank variable
    • you can change data types, it is loose
  • const
    • doesn’t change
    • can’t create blank const
  • symbols table - like a database (“warehouse”) which lets us access symbols (e.g. Window object)

9 - Arithmetic operator’s and BODMAS

  • operators - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
  • BODMAS
    • B - () brackets, precedence 20 (highest)
    • O - pOwers - function call, precedence 18
    • DM - division and multiplicaton, precedence 14
    • AS - addition and substraction - precedence 13
  • modulo - remainder after division

10 - Assignment operator’s

  • +=, -=, *=, /=, %=, **=
  • polymorphism - “string” + 10 -> “string10”

11 - Code editors and debugging

  • nothing interesting really

12 - Function and subroutines

  • like routine in daily life - set of instructions that can be ren at a certain point in time
function makeCoffee (parameters) { // parameters are variables
    ...
}

makeCoffee (argument); // arguments are values
  • parameters are deleted after use, we want them only while execution
  • variable inside a function is also disposable
Function
Function

13 - Objects and arrays

Objects

{
    color : "red",
    speed : 165,
    maker : "Volvo",
    drive : function() {...},
    stop  : function() {...}
}
  • color - key name
  • “red” - value
  • color: “red” - property
  • drive - function() - subroutines/functions inside object is method
  • drive - key name
  • funciton() {…} - set of instructions

Arrays

  • arrays are list object
  • kinda like shopping list
  • each array has length property
[
    0 : "Apple",
    1 : "Orange",
    2 : "Pear"
]
  • 0 - key name
  • Apple - item
  • 0 : “Apple” - element
  • zero index
var variable = []; // array literal

14 - Embedding objects & arrays

  • target arrays
var embed = ["hello", 20, ["embedded", 999], "end"];
embed[2][0]; // -> "embedded"
embed.length; // -> 4
embed[2].length; // -> 2

var car = {
    make: "volvo",
    speed: 160, // property
    engine: { // property
        size: 2.0,
        make: "bmw",
        fuel: "petrol",
        pistons: [ { maker: "BMW" }, { maker: "BMW" } ]
    }
    drive: function(){ return "drive"; } // method
}

var array = [
    "string",
    100,
    [ "embed", 200],
    {car: "ford"},
    function(){ return "drive"; } // we cannot define name for function within array
];

15 - Object & array member access, deletion & creation

var obj = {}; // -> {} is object literal

obj = {
    number: 999,
    string: "hello",
    formula: 5 + 5,
    later: null
}

console.log(obj.formula); // -> 10

obj["number"]; // -> 999
obj[number]; // -> number is not defined, it is fetching variable

var getProperty = "formula";
getProperty;
obj[getProperty]; // -> 10

array

obj = {
    0: 999,
    123: "hello"
}

obj[0]; // -> 999
obj[123]; // -> hello

16 - Key creation, assignment, deletion & embedded objects

obj.added = "new value"; // add property
delete obj.added;   // remove property, returns true, better than setting it to null


obj = { hello: "helloWorld", embed: { level2: 200, 1: "yup" }};
obj.embed.level2; // -> 200, more convenient
obj["embed"]["level2"]; // -> 200, more suitable for dynamic fetching

obj.embed[1]; // -> yup
obj.["embed"][1]; // -> yup

17 - Member creation, assignment & deletion

todo

18 - Prototype

  • prototype - shared object
  • it allows us to control our code much more
  • it is created automatically when we make an object
  • array is structured and comes with lots of methods
    • push, pop, slice…
apple = {
    color: "red",
    width: 200,
    height: 150
}

prototype = {
    eat: function() {...},
    throw: function() {...},
    nibble: function() {...}
}

apple.throw();

19 - Constructors

function ConstructApple() { // capital letter for constructors
    console.log(this);

    this.color = "red";
    this.width = 200;
    this.height = 300;
}

ConstructApple.prototype = {
    eat: function() { return 'eat an apple'; }
    throw: function() { return 'THROW IT!'; }
    nibble: function() { return 'nibble like a hamster'; }
}

var apple = new ConstructApple(); // new makes empty object and sets context
var apple2 = new ConstructApple();
var apple3 = new ConstructApple();
  • every object has its defined properties and prototype functions are attached
  • ConstructApple().prototype means run prototype
  • ConstructApple.prototype means attach prototype

20 - Constructors Part 2

  • this is reference to an object
  • if compiler doesn’t know the context for this, it defaults to window object
apple.color = "green"; // change values of one object
ConstructApple.prototype.someName = "hello apple!"; // add shared property to prototype, eg. all objects

// set dynamically on construction
function ConstructApple(color, width, height) { // arguments
    console.log(this);

    this.color = color;
    this.width = width;
    this.height = height;
}

var apple = new ConstructApple("red", 200, 300); // parameters
var apple2 = new ConstructApple("green", 100, 150);
var apple3 = new ConstructApple("yellow", 250, 200);

21 - Scope

  • scope = access, example of big building with rooms with restricted access

global scope

  • accessible for anybody, attached to window object

object scope

  • scope inside {}
var hello = { inner: { code: "1234", inner: { finish: "fini"} } }; // three scopes
hello.inner.code; // -> "1234"
hello.inner.inner; // -> Object { finish: "fini"}
hello.inner.inner.finish; // -> "fini"

function scope

function test() {
    var loz = "lawrence"; // it is within {}
    return loz;
}

test(); // -> "lawrence". It looked in the scope and find it.
loz; // -> Error. It is not in window object, it is not global variable.

var globe = "global scope";
globe; // -> "global scope"
function test() { return globe;}
test(); // -> "global scope" - checks local scope first, then global

function text() { var globe = "inner test"; return globe;}
test(); // -> "inner test"
globe // -> still "global scope"

// set global var from within a fuction
function test() { hello4 = "inf global" } // ommiting var makes it global

22 - Conditional Operators

assignment operator

= - assign value or property

comparison operator

== - case sensitive 20 == "20" -> true, due to polymorphism false == 0 -> true true == 1 -> true false == 1 -> false null == undefined -> true, due to polymorphism

  • better (then ===) for checking empty variable a == undefined

comparison operator for type, too

=== - checks value and data type, preferred method 20 === "20" -> false null === undefined -> false false === 0 -> false true === 1 -> false

do not match

!= - is not equal to

"answer" != "correct answer" // -> true, they're not the same

20 != "20" // -> false, due to polymorphism

triple do not match

!== - prevents polymorphism

20 !== "20" // -> true

greater, less than…

>, <, <=, >= - demands number values

20 > 5 // true
2 > 5 // false
20 >= 20 // true

23 - If statements

|| - or (at least one is true) && - and (everything must be true)

if(a === "something") {
    return "It's true!";
} elseif(a === "something else") {
    return "Something else it is!";
} else {
    return "Not true, a doesn't equal something";
}



var check = "cake";
var score = 0; // optional, recommended

if (check === "cake" || check === "cup cake"){
    
    score = 1; // no var, so it's global. Assign value if already present
    console.log("correct, your score is now: " + score);

} else {
    
    score = 0;
    console.log("wrong, your score is now: " + score);

} // no need to put ;, cause JS knows it is execution content

24 - If statements Part 2

  • talk about precedence levels
var score = 12,
    players = 6;

if (score === 12 && players === 6) {
    console.log("Statement is true");
} else {
    console.log("Statement is false");
}

25 - For loop

  • incredible fast loop, the fastest in JS
  • i++ is incrementing
  • i-- is decrementing
var array = [];

for (var i = 0; i <= 99999; i++) { // careful of infinity condition, don't forget var keyword
    array.push(i); // push into array
}

console.log(array);

26 - Practical For loops

var array = ["hello", "world", 200];

for (var i = 0; i < array.lenght; i++) {
    console.log(array[i]);
}


// Dynamically get values from an object
var obj = {color: "red", width: 200, height: 300}
var a = Object.keys( obj ); // fill array with keys form variable obj

for (var i = 0; i < a.lenght; i++) {
    console.log(obj[ [i] ]); // it is like obj["color"]
}

27 - Understanding the document object

  • SWEET STUFF here
  • HTML and CSS gets rendered, JIT compiler will make javascript representation of the DOM. Big object populated with another objects
  • globally accessible
  • dir( document ) in console gives js object and you can see what you can manipulate with!

28 - Targeting DOM elements

  • all DOM elements are converted into JS objects
  • js is case sensitive
document.getElementById("hello"); // fetch an js object representing that node

dir( document.getElementById("hello") ); // print actual interactive object

dir( document.getElementsByTagName("div") ); // print in console an array representing <div> tag

dir( document.getElementsByClassName("two classes"); // elementS - will return array with elements which have both classes

dir( document.querySelectorAll('#css, .selector name') ); // returns always array

29 - Event Handlers

  • event listeners - listening what is user doing, enables us to make interactive behaviour
<body>
   <input id="eventClick" type="button" value="click me!"> 
</body>
dir( document.getElementById("eventClick") ); // we can take a look at available events, someone them maybe won't apply (onplay for example)

// on click event - not recommended
document.getElementById("eventClick").onclick = function(){ // we reassign value of property onclick to function
    alert("hello world");
};

// addEventListener - recommended native way, much faster

// omit 'on' otherwise it could interfere with property
// add function as second parameter
document.getElementById("eventClick").addEventListener("click", function(){
    alert("hello world");
});

// addEventListener - possible to have multiple events, cause it doesn't override previous one
document.getElementById("eventClick").addEventListener("click", function(){
    alert("another dialog");
});
  • addEventListeners can’t be removed, because functions are anonymous

  • the right way is to make concrete function and call it from listener

function eventClicker() { // global function
    alert("hello world");
}

document.getElementById("eventClick").addEventListener('click', eventClicker);
document.getElementById("eventClick").removeEventListener('click', eventClicker);

30 - This keyword explained

  • change based on context, defaults to window object
  • use strict - tell compiler to comply with ES5 standards
"use strict";

var obj = {
    name: "Johnny",
    inner: {
        lastName: "Hajek",
        test: function() {console.log(this);}
    }
    test: function() {console.log(this);}
}

function test() {
    console.log(this);
}

test(); // -> without strict mode returns window object
        // -> with strict mode returns undefined

obj.test(); // -> returns obj object
obj.inner.test(); // -> returns obj.inner object

document.getElementById("eventClick").addEventListener('click', function() {
    console.log(this); // -> this = element that was clicked on
});
This
This

31 - Changing elements’ content

<body>
    <div id="changeMe">Hello world</div>
    <input type="button" id="eventClick" value="Click me!">
</body>
// change text contents of element
document.getElementById("changeMe").innerText = "goodbye!"; // modifying innerText property, can't add html tags (it'd escape special characters)

// replace html content
document.getElementById("changeMe").innerHTML = "<span>X</span> goodbye!";

// add html to content
document.getElementById("changeMe").innerHTML += "<span>X</span>!"; // += add in the and of element, this operators also polymphors

// change nested html element
document.querySelectorAll("#changeMe > span")[0].innerText = "change me"; // it is array, to access we need point in an array with [0]

// change self closed element's value
document.getElementById("ChangeMe").value += "yes!";

32 - Changing element styles

  • we can’t find computed style properties via JS, only those inlined in HTML
// find value of computed CSS property
getComputedStyle( document.getElementById('blue') ).getPropertyValue('width'); 

// find value of inlined CSS property
document.getElementById('red').style.backgroud; // -> "red"

// assign inline style
document.getElementById('red').style.backgroud = "#bada55"; // hsl, hsla, color name...whatever

// more advanced property
document.getElementById('red').style.borderRadius = "5px"; // get rid off the hyphens, camelCase

33 - Create and append DOM element

document.body.innerHTML =+ '<div></div>'; // one way

// create **virtual DOM** object
// required parameter (html element)
var DOMobject = document.createElement('div'); // this doesn't create html object, since js works with its own virtual DOM

DOMobject // -> <div></div>
dir( DOMobject ); // -> div object

// modify our DOMobject
DOMobject.id = "myDiv";
DOMobject.style.width = "300px";
DOMobject.style.height = "300px";
DOMobject.style.background = "#bada55";
DOMobject.innerText = "This is my div!";

DOMobject // <div id="myDiv" style="..."></div>, currently only in JS

document.body.appendChild(DOMobject); // insert into body (specified element)

var spanElement = document.createElement('span'); // create span
spanElement.innerText = "this is inner span"; // add text
document.getElementById("myDiv").appendChild(spanElement); // insert in #myDiv

// quicker method for simple inserts
document.getElementById("myDiv").innerHTML("<span>..</span>");

DOMobject.style.background = "red"; // it works, relationship between virtual and actual element is maintained

34 - Final project

// add div#myDiv
var myDiv = document.createElement('div');

myDiv.id               = "myDiv"
myDiv.style.width      = '100px';
myDiv.style.height     = '100px';
myDiv.style.background = 'red';

document.body.appendChild(myDiv);


// These aren't DRY

// add options
var colors  = ['red', 'green', 'blue'];
var widths  = ['100px', '200px', '300px'];
var heights = ['100px', '200px', '300px'];

// add selects
var selectColors  = document.createElement('select');
selectColors.id   = 'background';
var selectWidths  = document.createElement('select');
selectWidths.id   = 'width';
var selectHeights = document.createElement('select');
selectHeights.id  = 'height';

// fill the selects
for ( var i = 0; i < colors.length; i++) {
    selectColors.innerHTML += '<option value="' + colors[i] + '">' + colors[i] + '</option>';
}

for ( var i = 0; i < widths.length; i++) {
    selectWidths.innerHTML += '<option value="' + widths[i] + '">' + widths[i] + '</option>';
}

for ( var i = 0; i < heights.length; i++) {
    selectHeights.innerHTML += '<option value="' + heights[i] + '">' + heights[i] + '</option>';
}

// create the selects
document.body.appendChild(selectColors);
document.body.appendChild(selectWidths);
document.body.appendChild(selectHeights);


//-------------------------------------------------------------
// the real thing

// make array of selects
var arraySelect = document.getElementsByTagName('select');
var element = document.getElementById('myDiv'); // searching can be expensive object, it is better to prepare variable before reusing many times (e.g. animation)

// var name = function() {...}  this and... 
// function name() {...}        ... this is quite the same (probably)

var changeProp = function() {
    var style = this.id; // ID have to have a name corresponding with CSS property
    var value = this.value; // selected option in set to be select's current value

    element.style[style] = value; // dynamically fetch a key with []
}

for ( var i = 0; i < arraySelect.length; i++) {
    arraySelect[i].addEventListener('change', changeProp); // change - what had been chosen
}