All posts by admin

Data types, variables for JS

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures

Quick Tip: How to Declare Variables in JavaScript

Data types
The latest ECMAScript standard defines seven data types:

Six data types that are primitives

Boolean
Null
Undefined
Number
String
Symbol (new in ECMAScript 6)
and Object

All types (except objects) define immutable values (values, which are incapable of being changed). For example and unlike to C, Strings are immutable. We refer to values of these types as “primitive values”.

Integer type
Size: 8 bytes (2 ^ 64 bits allowed values)
Allowed values: 18437736874454810624 finite numbers (half positive half negative, including positive and negative zero) and three symbolic values NaN, Positive Infinity & Negative Infinity

Integers can be expressed in decimal (base 10), hexadecimal (base 16), octal (base 8) and binary (base 2).

A decimal integer literal consists of a sequence of digits without a leading 0 (zero).
A leading 0 (zero) on an integer literal, or a leading 0o (or 0O) indicates it is in octal. Octal integers can include only the digits 0-7.
A leading 0x (or 0X) indicates a hexadecimal integer literal. Hexadecimal integers can include digits (0-9) and the letters a-f and A-F. (The case of a character does not change it’s value, e.g. 0xa = 0xA = 10 and 0xf = 0xF = 15.)
A leading 0b (or 0B) indicates a binary integer literal. Binary integers can only include the digits 0 and 1.

Some examples of integer literals are:

0, 117 and -345 (decimal, base 10)
015, 0001 and -0o77 (octal, base 8)
0x1123, 0x00111 and -0xF1A7 (hexadecimal, “hex” or base 16)
0b11, 0b0011 and -0b11 (binary, base 2)

Boolean type
Boolean represents a logical entity and can have two values: true, and false.

The Boolean type has two literal values: true and false.

Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object. The Boolean object is a wrapper around the primitive Boolean data type.

If we evaluate “undefined” or “null”, it is false.
If we pass them into a Boolean object, it evaluates to true. This also applies for ‘false’.

For example, the condition in the following if statement evaluates to true:

This behavior does not apply to Boolean primitives. For example, the condition in the following if statement evaluates to false:

Do not use a Boolean object to convert a non-boolean value to a boolean value. Instead, use Boolean as a function to perform this task:

If you specify any object, including a Boolean object whose value is false, as the initial value of a Boolean object, the new Boolean object has a value of true. That’s because an Boolean Object instance does not return primitive true or false. It returns an object and will evaluate to true.

Do not use a Boolean object in place of a Boolean primitive.


output:

its true! 😀
bool is true
bool2 is true
bool4 is true

Null type
The Null type has exactly one value: null. See null and Null for more details.

Undefined type
A variable that has not been assigned a value has the value undefined. See undefined and Undefined for more details.

String types

JavaScript is case-sensitive and uses the Unicode character set.

JavaScript’s String type is used to represent textual data. It is a set of “elements” of 16-bit unsigned integer values.
There are 2^16 (or 0-65535), 0xFFFF representations of text. The encoding is UTF-16, So 0-65535 text representations are mapped from UTF-16. You can view the table at https://upload.wikimedia.org/wikipedia/commons/0/01/Unifont_Full_Map.png
Top is 0 to FF. Left side is 0 to FF. Thus, 0xFFFF is 0-65535.

ref – http://chineseruleof8.com/code/index.php/2017/06/07/unicode/

JavaScript strings are immutable (unchangeable), once a string is created it is impossible to modify it. However, it is still possible to create another string based on the original by using string functions such as substr and concat.

An empty string has length zero and therefore contains no elements.

String literal

“string here” + “haha” + etc.

ES6 template literals, as the name suggests, come with a new literal syntax. They use back ticks ( ) to denote the start and end (just like strings use quote marks (‘ ‘ or ” “)). Within those back ticks, Template literals are parsed at runtime, to provide some new features.

A decimal integer literal consists of a sequence of digits without a leading 0 (zero). A leading 0 (zero) on an integer literal, or a leading 0o (or 0O) indicates it is in octal. Octal integers can include only the digits 0-7. A leading 0x (or 0X) indicates a hexadecimal integer literal.

An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets ( [] ). When you create an array using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified

The following example creates the coffees array with three elements and a length of three:

If an array is created using a literal in a top-level script, JavaScript interprets the array each time it evaluates the expression containing the array literal. In addition, a literal used in a function is created each time the function is called.

Extra commas in array literals
You do not have to specify all elements in an array literal. If you put two commas in a row, the array is created with undefined for the unspecified elements. The following example creates the fish array:

This array has two elements with values and one empty element (fish[0] is “Lion”, fish[1] is undefined, and fish[2] is “Angel”).

If you include a trailing comma at the end of the list of elements, the comma is ignored. In the following example, the length of the array is three. There is no myList[3]. All other commas in the list indicate a new element.

Note : Trailing commas can create errors in older browser versions and it is a best practice to remove them.

In the following example, the length of the array is four, and myList[0] and myList[2] are missing.

In the following example, the length of the array is four, and myList[1] and myList[3] are missing. Only the last comma is ignored.

Object Literal

An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}).

Additionally, you can use a numeric or string literal for the name of a property or nest an object inside another. The following example uses these options.

console.log(unusualPropertyNames.”); // SyntaxError: Unexpected string
console.log(unusualPropertyNames[”]); // An empty string
console.log(unusualPropertyNames.!); // SyntaxError: Unexpected token !
console.log(unusualPropertyNames[‘!’]); // Bang!

Variables

Declaration: The variable is registered using a given name within the corresponding scope (explained below – e.g. inside a function).

Initialization: When you declare a variable it is automatically initialized, which means memory is allocated for the variable by the JavaScript engine.

Assignment: This is when a specific value is assigned to the variable.

Declaration Types
Note: while varhas been available in JavaScript since its initial releast, letand const are only available in ES6 (ES2015) and up.

This declaration is probably the most popular, as there was no alternative until ECMAScript 6. Variables declared with var are available in the scope of the enclosing function.

Example:

If there is no enclosing function, they are available globally.’

// https://stackoverflow.com/questions/36797206/what-is-the-symbol-primitive-data-type-in-javascript?noredirect=1&lq=1

They prevent using a simple string to reference the field, so only consumers with the symbol can gain access.
So consumers can’t just create a string and access stuff from the object.

In general, symbols are intended as a replacement for magical names. Rather than having a properties simply called ‘foo’, you can allocate a symbol const foo = Symbol() and pass that selectively.

Symbol Type

How they are stored

jQuery lazy loading

Loading the library

Targeting it…and callbacks

Specifying the images

Since your jQuery targets class lazy, we must use lazy for classes on img and div tags.
You use data-src to specify the location of the images.

Note that for img tags, when the images load, it will change to data-src will change to src.
However, if you were to use div, data-src will change to background-image: url(….) .

instanceof

ref – http://chineseruleof8.com/code/index.php/2018/02/06/prototype-and-inheritance-in-js-non-class/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof

So we create an instance of CoverArticle called c.
It accesses its own prototype function coverArticleFormat.
It goes up the hierarchy one step and goes into Cover prototype where it accesses coverFormat.
It goes one more step to Image prototype, and accesses print.

Instance of lets you know if your object can access functionalities from the specified Constructor.

Because instance c is at the highest level of the hierarchy. When it can’t find a functionality, it goes down to Cover Prototype Object. When it can’t find it there, it goes to Image Prototype, and fianlly Object Prototype. Hence, it can touch all Prototype Objects of the constructors. That’s why it is true.

When analyze the cover1 instance shown in the diagram, which of prototype Cover, we see that it can access its functionalities from its own Prototype Cover. It can go up to Image Prototype and Object Prototype. However, it ends there. It cannot go backwards and access CoverArticle prototype at all. Hence, false.

isPrototypeOf

isPrototypeOf is a function on the Object Prototype that tests whether the parameter can check against the prototype.
So for example, if we have an instance of CoverArticle (like c) it can definitely touch Cover.
If we have instance of Cover (like cover1) obviously it touches Cover.

buddha, an instance of Image, only touches Image and Object. It cannot go backwards and check Cover Prototype Object. Thus, it will be false.

ref – https://stackoverflow.com/questions/2464426/whats-the-difference-between-isprototypeof-and-instanceof-in-javascript

instanceof vs isPrototypeOf

instanceof and isPrototypeOf, they do the same thing, both traverse up the prototype chain looking for an specific object in it.

The difference between both is what they are, and how you use them,

isPrototypeOf is a function available on the Object.prototype object it lets you test if an specific object is in the prototype chain of another, since this method is defined on Object.prototype, it is be available for all objects.

instanceof is an operator and it expects two operands an object and a Constructor function, it will test if the passed function prototype property exists on the chain of the object (via the [[HasInstance]](V) internal operation, available only in Function objects).

Why do we use a temporary box in prototype inheritance?

https://stackoverflow.com/questions/47843315/why-do-we-use-a-temporary-box-in-prototype-inheritance

The function below is one that Derek Banas on youtube on his OO Javascript tutorial uses.

You have a function A that you want as a child. You have function B that you want as a parent.
You want to connect them using a function called extend.

The implementation is:

but why is this so?

Prototype objects are single literal objects. We need to create a Temp function that points to the Parent prototype object first, then spawn a instance, which acts as a single literal object.

This single instance will act as the Child’s Prototype Object, which is connected to Parent’s Prototype object.

1) Creating a custom Child Prototype object.

It should be done by like so:

which will give you an empty object with its __proto__ pointing to Foo’s prototype object. However, since we’re gunna do it by hand, we’ll do it step by step.

Setting up Child Prototype Object

First, we create the function Parent. By default, it will have a literal object called Parent Prototype. This Parent Prototype will have __proto__ pointing to default Object Prototype.

– Parent will have a ‘prototype’ reference to Parent Prototype
– Parent Prototype will have a ‘constructor’ reference to Parent

In order to create a Child Prototype Object, we first must create a function Temp to estabblish a Temp setup. The Temp will have a prototype reference to a Temp Prototype object. The Temp Prototype will have a constructor reference back to the temp. And by default, the Temp Prototype will have a __proto__ to the default Object Prototype, as shown in the diagram.

Then, with this setup, if we create an instance of Temp, that instance of Temp, will have its __proto__ pointing to Parent Prototype. We then call this new Temp object “Child Prototype Object”

From here, when we instantiate a child object, it will have its __proto__ pointing to Child Prototype Object. We can access any functions declared there. If it doesn’t exist, it will go up the hierarchy tree via __proto__, which is Parent Prototype. If it does not find it there, it goes up the next __proto__, which is the Object Prototype. And if its not there, then what we’re looking for does not exist.

Object.create

ref – https://stackoverflow.com/questions/62378057/what-is-the-difference-between-object-assignment-and-object-create

Object.create(param) creates an empty object, with its __proto__ pointing to “param”. That way, the empty object can inherit properties from param.

We’ll demo this by first creating a literal object with “person” variable referencing it.

Now, in JS, the base Object class is an object that has a prototype reference that points to an Prototype Object. Its Prototype Object then has a constructor reference pointing back to the Object class.

Every object created in Javascript, will have its reference __proto__ pointing to Object’s Prototype Object. This situation is shown in the diagram:

Notice Object’s Prototype Object has a __proto__ pointing to null. __proto__ is the reference that indicates which object you inherit from. Thus, since our base class Object is the parent class of every object, it does not inherit from anyone. Thus, its Prototype Object’s __proto__ will be null.

Our person object will have its __proto__ pointing to the Object’s Prototype Object. This means our object derives from Object.

Create empty object and inherit from person object

We create an empty object called me, that extends from the person object we just created.
We do this like so:

1) Object.create will create an empty object
2) It will then point the empty object’s __proto__ reference to our person object

For completion purposes, let’s just add property “name” and initialize it to “Matthew”.

Now, using the me object, we can access its inherited properties from the person object. The reason why we can call printIntroduction is because me’s __proto__ points to person. It is set automatically by Object.create.

Let’s check out what the me object looks like.

We’ve accessed the function printIntroduction through me. Now let’s access the property isHuman.

Extending an Object

Previously, we’ve extend a literal object. Now, let’s extend a function object so that when we instantiate it by using new, all the instantiations will have the same inheritance.

First, let’s create a function called CoolPerson.

Basically, CoolPerson is a function object. This function object has a prototype reference to another Object (CoolPerson Prototype Object) that houses all a lot of properties and functions. It includes the constructor, which points back to function CoolPerson, and also a __proto__ that points to Object’s prototype object.

Let’s verify by logging CoolPerson, and its references.

console.log(CoolPerson) // [Function: CoolPerson] or f CoolPerson

Check out the output to make sure everything checks through.

Re-point prototype, creating a constructor and pointing it to the correct function

Previously, from above, we created a person object. It is a literal object that derives from base Object’s prototype.

When you try to access ‘constructor’, it will first see that person itself does not have a constructor property. We use hasOwnProperty to do this. However, when we do access the constructor, we see that it points to the default Object. This is because person uses its inheritance via __proto__ and finds that inheriting from Object’s Prototype Object, it does have a constructor property. This constructor property points to native Object.


> person
{isHuman: false, printIntroduction: ƒ}
> person.hasOwnProperty(constructor)
false
> person.constructor
ƒ Object() { [native code] }

1) Thus, first we need to repoint our prototype to person. What this means is that any instantiations created with “new” will inherit from peron.
2) we then need to create a property called constructor and attach it to person. This is so that the instantiations of CoolPerson will display their correct type. If you don’t do this, the instantiations will have type “Object”, instead of type “CoolPerson”.

Now, we can instantiate c. We are able to use property name from its original definition, and also access inherited properties from person object, such as isHuman, and printIntroduction.

Instantiation using inherited functionalities

The diagram for function CoolPerson that inherits from person object looks like this:

You’ll notice that an instance of CoolPerson will always inherit from the person object via its __proto__ reference. When a function definition in the person object accesses the ‘this’, the ‘this’ refers to the instance itself.

When instance c was made from function CoolPerson, it copies all the properties, including ‘name’. Thus, instance c has its own name. Once it access the singleton person object and sees this.name, it knows that this refers to the instance itself. And looks to see if there is a name property in the instance. It does, and hence it will use the name property in the instance.

Another Example

Connecting Hierarchy

Say we want to extend Person.
1) Create Student function object
2) const protoObj = Object.create(Person.prototype) // this creates an object with proto pointing to Person.prototype
3) Student.prototype = protoObj
4) protoObj.constructor = Student

So now when you create an instance say

OOP in Javascript (with Node)

ref – http://book.mixu.net/node/ch6.html

The new constructor call (e.g. new Foo()):
creates a new object,
sets the prototype of that object to Foo.prototype and
passes that as this to the constructor.

The prototype chain lookup mechanism is the essence of prototypal inheritance.

Instantiate the class:

Adding private variables

Avoid assigning variables to prototypes

If you want to define a default value for a property of an instance, define it in the constructor function.

Prototypes should not have properties that are not functions, because prototype properties that are not primitives (such as arrays and objects) will not behave as one would expect, since they will use the instance that is looked up from the prototype. Example for Dimitry Sosnikov’s site:

Hence prototypes should only define methods, not data.

static vs non-static

ref – https://stackoverflow.com/questions/45594196/difference-between-static-function-declaration-and-the-normal-function-declarati

That’s the very definition of a static function that you don’t have to instantiate the class to call it. That’s not something JS specific.

A static method is callable from the class itself

A non-static method is callable from an instance of the class, so you basically have to create an object before being able to access that method.

Although in the end, both is just little more than:

es6 classes just make it look nicer. Syntactical sugar.

For example, for a addNumbers(var a, var b) which does return a+b, is it really necessary to waste memory instantiating an object of the class just to add those 2 numbers? No, you just need the result and that’s the whole point of having static.

Using the first style allows you to group methods in a particular class (think of something like namespaces). Maybe you can define classes like Math and String, which both have the add method but implemented in a different way. Calling add() by itself would be confusing, but Math.add() and String.add() are not.

Freeze Screen in Chrome Debugger for popover Inspection

https://stackoverflow.com/questions/17931571/freeze-screen-in-chrome-debugger-devtools-panel-for-popover-inspection

  • Browse to the desired page
  • Open the dev console – F12 on Windows/Linux or option + ⌘ + J on OSX
  • Select the Sources tab in chrome inspector
  • In the web browser window, hover over the desired element to initiate the popover
  • Hit F8 on Windows/Linux (or fn + F8 on OSX) while the popover is showing. If you have clicked anywhere on the actual page F8 will do nothing. Your last click needs to be somewhere in the inspector, like the sources tab
  • Go to the Elements tab in inspector
  • Find your popover (it will be nested in the trigger element’s HTML)

function expression vs declarations (js)

ref – https://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/

Quick Tip: Function Expressions vs Function Declarations

What is a Function Declaration?

A Function Declaration defines a named function variable without requiring variable assignment.

Function Declarations occur as standalone constructs and cannot be nested within non-function blocks.

It’s helpful to think of them as siblings of Variable Declarations. Just as Variable Declarations must start with “var”, Function Declarations must begin with “function”.

a function declaration:

ECMA 5 (13.0) defines the syntax as
function Identifier ( FormalParameterListopt ) { FunctionBody }

Similar to the var statement, function declarations are hoisted to the top of other code.

What is a Function Expression?

A Function Expression defines a function as a part of a larger expression syntax (typically a variable assignment ). Functions defined via Functions Expressions can be named or anonymous.

Function Expressions must not start with “function”
Rather, they start with a var reference, or a parentheses.

more examples:

Function expressions aren’t hoisted, which allows them to retain a copy of the local variables from the scope where they were defined.

Benefits of Function Expressions
There are several different ways that function expressions become more useful than function declarations.

As Closures

Closures are used when you want to give parameters to a function, before that function is executed. A good example of how this can benefit you is when looping though a NodeList. A closure allows you to retain other information such as the index, in situations where that information will no longer be available when the function is executed.

Let’s create a unordered list with class “tab”:

Then we loop over the elements, and assign it a click event like so:

Note that, tabs[i] is an HTML Element object. It has an “onclick” callback handler.
We need to provide it a function so that the HTML element tabs[i] has a callback function to execute after running its own code.

the HTML element tabs[i] will also pass event object (filled with info on the click itself)
thus, when we click, it’ll call our “standardFunction”
and also we get to analyze (and use) an event object.

In terms of scope, you can access parent’s scope variable i. However, note that the loop runs first, going from 0 to 2, and assigning all callback functions first in the process. After it finishes assigning the function, the i is at 2.

When you click, the callback will execute and since our scope is parent, it will access i, which is 2.

This isn’t what we want. We want to keep track of the index.

Solution

The solution to keeping track of this index is to use a closure. Closures are objects and depending on implementation (gets moved around from stack to heap). Its a way to reference scope and variables. In our case, we first create a function called rickysHandler where we pass in the index i.

rickysHandler’s has a inner function called tabClickEvent, which is returned to a tab’s onclick.
Whenever a click happens, it will execute this tabclickEvent.

rickysHandler takes the index and creates a closure for tabClickEvent. Under the hood, whenever tabs[i].onclick gets assigned to a rickysHandler(i), it creates a closure where i lives. And then the function tabClickEvent references it.

so tabs[0].onclick references its own function tabClickEvent, where it reference a closure with index 0
so tabs[1].onclick references its own function tabClickEvent, where it reference a closure with index 1
so tabs[2].onclick references its own function tabClickEvent, where it reference a closure with index 2

like so:

Passing as Arguments

Function expressions can be passed directly to functions without having to be assigned to an intermediate temporary variable.
The Array prototype has a forEach function can use to iterate through all the elements. The forEach function takes a function expression. We create an anonymous function expression and pass it in.

As Immediately Invoked Function Expressions (IIFE)

IIFE’s are used to help prevent your functions and variables from affecting the global scope. All the properties within are scoped to the anonymous function. This is a common design pattern that’s used to prevent your code from having unwanted or undesired side-effects elsewhere.

It’s also used as a module pattern to contain blocks of code in to easy to maintain sections.

localhost Mongo set up and usage for Slideshow-Backend

https://github.com/redmacdev1988/SlideShow-Backend

Running your backend locally

1) open terminal and type “mongod” in order to start your mongo db.
2) pull down the project SlideShow-Backend onto your desktop
3) open a new terminal and cd into the SlideShow-Backend directory
4) then type “npm start”
5) you will the server starting up:

[nodemon] 1.14.11
[nodemon] to restart at any time, enter rs
[nodemon] watching: *.*
[nodemon] starting node index.js
Serving up files in ‘views’ folder
Serving up files in ‘Images’ folder
index.js –  created model loading here
index.js –  mongoose instance connection url connection
index.js –  routes speicfied
 pictorial list RESTful API server on: 8080

6) Open a browser and go to: http://localhost:8080/

You should see the list of image strings appear as an array on the browser. This list of image names are images that were included in the project directory under SlideShow-Backend/Images/your-image.jpg

for example:

SlideShow-Backend/Images/railay-ocean.jpg
SlideShow-Backend/Images/tiantian-buddha.jpg

In your local environment, set up mongo. Then use a terminal and set up your mongo db with database “PictorialDB”.

> show dbs
BadmintonSubscriberDatabase 0.000GB
EventsDB 0.000GB
PictorialDB 0.000GB
admin 0.000GB
local 0.000GB

Start up your mongo database

EPCNSZXW0324:~ $ mongod

2018-03-30T16:25:09.506+0800 I CONTROL [initandlisten] MongoDB starting : pid=17616 port=27017 dbpath=/data/db 64-bit host=EPCNSZXW0324.princeton.epam.com
2018-03-30T16:25:09.507+0800 I CONTROL [initandlisten] db version v3.4.10
2018-03-30T16:25:09.507+0800 I CONTROL [initandlisten] git version: 078f28920cb24de0dd479b5ea6c66c644f6326e9

sign into your mongo db

Last login: Fri Mar 30 16:23:35 on ttys002
EPCNSZXW0324:~ rickytsao$ mongo
MongoDB shell version v3.4.10
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.10

create pictorial db

> use PictorialDB
switched to db PictorialDB

Inserting data through code

First create a Schem for our pictorial. Then add it to module.exports for global usage.

PictorialModel.js

Once we make this model, whenever we insert into the database, we’ll see the row data there.

Then in your SlideShow-Backend app, implement create_a_pictorial where:
1) you get data from the body
2) Insert data into Pictorial
3) Finally, call the function “save” on the schema.

pictorialController.js

Then, check in your mongo db to verify:


> db.pictorials.find()

{ “_id” : ObjectId(“59fc081ff6cf8a0970256c38”), “name” : “railay-ocean”, “fileName” : “railay-ocean.jpg”, “description” : “I long to back here to swim”, “Created_date” : ISODate(“2017-11-03T06:09:35.515Z”), “__v” : 0 }
{ “_id” : ObjectId(“59fc0ca4f6cf8a0970256c39”), “name” : “tiantian-buddha”, “fileName” : “tiantian-buddha.jpg”, “description” : “It was a gray cloudy day, but was fun!”, “Created_date” : ISODate(“2017-11-03T06:28:52.385Z”), “__v” : 0 }

Check Images

1) Make sure you copy images into the Images folder at “SlideShow-Backend/Images”. i.e railay-ocean.jpg, tiantian-buddha.jpg, etc.

2) Now you can access images at http://localhost:8080/ImageName. This is where the app will go in order to retrieve images.