Sunday, July 21, 2019

Ubuntu - Useful Tricks


  • In Files, to jump to another folder directly, press Ctrl-L and type the path.   Also, it's useful to bookmark the root folder (go to it and bookmark it from the menu)

Friday, July 5, 2019

JavaScript (ES5) - Long-time Java Developer Notes on Differences and Important Features

This highlighting is used code quoted in the text.  All of the below is all EcmaScript5 or earlier versions.


Basics:

  • Strings
    • Single and double quotes - no diff
    • A quote inside: \' or \"

Variables:

  • var names: start with a letter, $ or _.  Can't start with a digit.  Can't be a reserved word.
  • declare a var : var varName;
    This var will be of type undefined without any type.
    Note: a variable used without first defining it, defines and uses a global variable which is equivalent to the code: window.myVar = ...
  • But this one : var varName2 = '234';
    will be of type string
  • And after this : varName2 = 234; (this is variable mutation i.e. it gets a new value)
    The varName2 became a variable of type numeric (dynamic typing)
  • types: string, numeric, xxx or yyy .  No int type.

Conditional processing:
  • A structure I have never met in Java:
       switch(true) {
          case age > 21 && height > 1.65:
             aaa = 123;
          case age >= 65:
             aaa = 222;
      }
  • Falsy: 
    • undefined
    • 0
    • false
    • null
    • NaN
  • Equality operator (==) performs a type conversion (it's called type coersion in JS) so that: 23 == '23' evaluates to true.  Also console.log('he is ' + age + 'years old'); is fine even when age is numeric./
  • Strict operator === means 'the same type and the same value'
  • If you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. For instanceif( typeof foo !== 'undefined' ) {...} but there is a function to check it, too.

Objects:

Primitive: a variable contains the value itself.
Object: the variable points to the object which is stored elsewhere.
  • Create objects (4 ways):
    • litera: var aaa = {name: "Ala", age: 53}   // it's an instance of Object() object
    • constructor methods (aka prototypes; not called classes):
      function Person(name, age) = {this.name = name, this.age = age};
      var p = new Person("Ala", 56)
        - it creates an empty objects and calls the constructor function with this set to the new object.
      • A method defined inside the constructor will not be shared among the children but separately recreated in each (memory!).  So, it's often better to Person.prototype.calcAge = function() {...}; instead.  This method will be shared by all children
    • Object.create(protoObject, { age: {value: 36}, fName: {value: 'Pawel'} }); but the 2nd parm is optional.  The value thing is not optional here.
  • Understand objects
    • An object in JS is simply a hashmap with key-value pairs. A key is always a string, and a value  can be anything including strings, integers, booleans, functions, other objects etc.
  • Create object, the minimalist version: var obj = {};
  • Always can extend an object from outside (No immutable objects?): obj['age'] = 56 or obj.age = 56
  • Or add a method
    obj.isAnAdult() { return this.age > 18; }  // the other syntax works, too
  • Functions are always objects (they're 1st class functions).  Create one, minimalist way function  foo() {}; and can add atributes or other methods the usual way: foo.age = 56
  • Summary: Practically everything is an object except primitive types (string, number and boolean), undefined and null (though null is considered an object, too).
  • If you want to know if a member exists independent but don't care what its value is:
    if ('membername' in object) // With inheritance VERIFY IF THIS ONE'S TRUE!!!
    if (object.hasOwnProperty('membername')) // Without in
    heritance
  • Clone: Object.assign(target, source)
    Watch out:  it is actually a merge of source into a target object, but Object.assign({}, source) will create a clone.  And, another warning: it's a shallow clone.
  • Inheritance is done in JS thru Prototype property which all objects have!!!  That property is used for children objects - any property or methods that we want the children objects to have access to, we put inside the Prototype property. The prototype property of object Object is null (here the protype chain stops when JS VM searches for a property or method of an object)

How does JavaScript work?

  • When method execution starts, first its execution context is created.
  • hoisting (during creation of the execution context for a method):
    • all declared functions are created before the execution for that method starts. But only declared function (not function expressions like var age = function(year) { ...}).  
    • thanks to hoisting, I can call functions that are declared later in the code.
    • all variables are created but set to undefined
  • Functions and only functions create a scope
    • Global scope is available to everyone
    • Functions written inside another function have access to the parent scope (or scopes if nested deeper)
  • Two types of functions:
    • regular (or declared) function - Just a function myFnc() {...}.
    • method - a function that is a value of an object (key, value) pair.
  • The this variable is part of the execution context and is set only at the moment when the function is called.  It's set to:
    • for regular functions, this is the Window object even if the function is defined inside of a method.
    • for method functions, the object in which the method is defined.

Interact with the Browser

  • DOM access: 
    • document.querySelector('#playerScore-' + activePlayer).textContent = score
      NOTE: querySelector finds only the first instance of a node satisfying the criteria
    • document.querySelector('.dice').style.display = 'none'
    • document.getElementById('player').classList.toggle('active')
  • Events:
    • Rule: Event gets processed only when the execution stack (where all exec contexts are placed) is empty (ie. all functions return)
    • When this happens the handler for the first of the events waiting in the event queue is called
    • doc.quSel(...).addEventListener('click', function() {....})
      arg1 - event type (see MDN for a table)
      arg2 - callback function

Console in the browser Dev Tools

  • > john - displays info about
  • > console.info(myArray) - displays more info than typing the object name directly
  • __proto__  - link to parent's prototype

Functions

  • IIFE ([ifee], Immediately invoked function expressions: (function (age) { var a = 5; ...})(5); .  The code inside the function is executed but variable a is hidden - data privacy. In JS, anything inside () is an expression.
    • Return from the function above an object with anything to be publicly available outside.
    • It's the module pattern
  • All functions in JS are closures.  Because functions have access to lexically outside scopes and (I think) scopes don't disappear.  Closures remember all vars and all parms of lexically outside functions.
  • Calling functions returned by functions: If fn1 returns a function, we can call it: fn1('John')(25);  where 'John' is an argument of fn1 and 25 is an argument of the functions that fn1 has returned.
  • Given, we have john object with a method presentation(style, timeOfDay) and emily object:
    • Function borrowing: john.presentation.call(emily, 'friendly', 'morning'); will execute the method for emily (every this will point to emily - use null if you don't need to redirect this)
    • Function borrowing with args in an array: john.presentation.apply(emily, ['friendly', 'morning']); 
    • Binding: 
      • var emilyFormal = john.presentation.bind(emily, 'formal'); will return a function with some parms preset (currying).  We can call it: emilyFormal('afternoon');.
      • Binding can also be used to set this for the function.