JavaScript Part 2

https://www.browserling.com/ gives you the ability to Live interactive cross-browser testing.

Using a function that returns another function. (This is a powerful JavaScript feature, typically called a closure.)  The function object created by a function literal contains a link to that outer context. This is called closure. This is the source of enormous expressive power.

All function parameters in JavaScript are passed by value, and there are no reference parameters. However, there are reference objects, such as arrays, which are passed to functions by reference.

JavaScript has function scope. This means that JavaScript does not have block scope, unlike many other modern programming languages. With block scope, you can declare a variable within a block of code and the variable is not accessible outside of that block.

Recursion

JavaScript experts recommend using the [] operator, saying it is more efficient than calling the  Array constructor.

shallow copy vs deep copy

javascript shift function:

redureRight

Jagged Arrays

peek vs pop

Priority Queues
In the course of normal queue operations, when an element is removed from a queue, that element is always the first element that was inserted into the queue. There are certain applications of queues, however, that require that elements be removed in an order other than first-in, first-out. When we need to simulate such an application, we need to create a data structure called a priority queue.

The linked list can be used in almost every situation where a one-dimensional array is used, except when you need random access to the elements of a list. When random access is required, an array is the better data structure to use.

A circularly linked list

Hashing is a common technique for storing data in such a way that the data can be inserted and retrieved very quickly. Hashing uses a data structure called a hash table. Although hash tables provide fast insertion, deletion, and retrieval, they perform poorly for operations that involve searching, such as finding the minimum and maximum values in a data set. For these operations, other data structures such as the binary search tree are more appropriate.

breadth-first search

Bubble sort in action

The Quicksort algorithm is best to use on large datasets; its performance degrades for smaller data sets.

There are two ways to search for data in a list: sequential search and binary search. A sequential search is used when the items in a list are in random order; a binary search is used when the items in a list are in sorted order. Binary search is the more efficient algorithm, but you also have to take into account the extra time it takes to sort the data set before being able to search it for a value.

The theory is that strong typing allows a compiler to detect a large class of errors at compile time. The sooner we can detect and repair errors, the less they cost us. JavaScript is a loosely typed language, so JavaScript compilers are unable to detect type errors. This can be alarming to people who are coming to JavaScript from strongly typed languages.

This is a bad thing because global variables are evil, and in JavaScript they are fundamental.

JSLint, a JavaScript parser that can analyze a JavaScript program and report on the bad parts that it contains. JSLint provides a degree of rigor that is generally lacking in JavaScript development. It can give you confidence that your programs contain only the good parts.

hasOwnPropery

Reflection

When a function is stored as a property of an object, we call it a method.

In many modern languages, it is recommended that variables be declared as late as possible, at the first point of use. That turns out to be bad advice for JavaScript because it lacks block scope. So instead, it is best to declare all of the variables used in a function at the top of the function body.

We can use functions and closure to make modules. A module is a function or object that presents an interface but that hides its state and implementation.

Since JavaScript’s arrays are really objects, the delete operator can be used to remove elements from an array:

delete numbers[2];
// numbers is [‘zero’, ‘one’, undefined, ‘shi’, ‘go’]

Unfortunately, that leaves a hole in the array. This is because the elements to the right of the deleted element retain their original names. What you usually want is to decrement the names of each of the elements to the right. Fortunately, JavaScript arrays have a splice method. It can do surgery on an array,

deleting some number of elements and replacing them with other elements. The first argument is an ordinal in the array. The second argument is the number of elements to delete. Any additional arguments get inserted into the array at that point:

numbers.splice(2, 1);
// numbers is [‘zero’, ‘one’, ‘shi’, ‘go’]

The property whose value is ‘shi’ has its key changed from ‘4’ to ‘3’ . Because every property after the deleted property must be removed and reinserted with a new key, this might not go quickly for large arrays.

CommonJs: synchronous require
This style uses a synchronous require method to load a dependency and return an exported interface. A module can specify exports by adding properties to the exports object or setting the value of module.exports.

AMD: asynchronous require
Asynchronous Module Definition
Other module systems (for the browser) had problems with the synchronous require (CommonJS) and introduced an asynchronous version (and a way to define modules and exporting values):

ES6 Modules
EcmaScript 6 adds some language constructs to JavaScript, which form another module system.

These global properties return a simple value; they have no properties or methods.

Infinity
NaN
undefined
null
Regex in Javascript

Positive Lookahead

When you want to know whether a pattern is found in a string, use the test or search method; for more information (but slower execution) use the exec or match methods.

Map, Keyed Collections

The WeakMap object is a collection of key/value pairs in which the keys are objects only and the values can be arbitrary values. The object references in the keys are held weakly meaning that they are target of garbage collection (GC) if there is no other reference to the object anymore. The WeakMap API is the same as the Map API.

Set Sample

Traditionally, a set of elements has been stored in arrays in JavaScript in a lot of situations. The new Set object, however, has some advantages:

Checking whether an element exists in an collection using indexOf for arrays is slow.
Set objects let you delete elements by their value. With an array you would have to splice based on a element’s index.
The value NaN cannot be found with indexOf in array.
Set objects store unique values, you don’t have to keep track of duplicates by yourself.

The use cases of WeakSet objects are limited. They will not leak memory so it can be safe to use DOM elements as a key and mark them for tracking
purposes.

Functional programming sample

Map reduce

Functional programming, no mutation.

Observables

 

JavaScript – walk-through – Part 1

In most languages, it is generally best to declare variables at the site of first use. That turns out to be a bad practice in JavaScript because it does not have block scope. It is better to declare all variables at the top of each function.
The lack of transitivity is alarming. My advice is to never use the evil twins. Instead, always use === and !== . All of the comparisons just shown produce false with the === operator.

It is recommended that you always use JSON.parse instead of eval to defend against server incompetence. It is also good practice for the day when the
browser provides safe data access to other servers.

undefined detection

When you evaluate a null variable, the null value behaves as 0 in numeric contexts and as false in boolean contexts. For example:

 

let vs var

Variable hoisting
Another unusual thing about variables in JavaScript is that you can refer to a variable declared later, without getting an exception.

const keyword

operators

Property names that are not valid identifiers also cannot be accessed as a dot (.) property, but can be accessed and set with the array-like notation(“[]”).

If the finally block returns a value, this value becomes the return value of the entire try-catch-finally production, regardless of any return statements in the try and catch blocks.

Starting with ECMAScript 6, JavaScript gains support for Promise objects allowing you to control the flow of deferred and asynchronous operations.

A simple example using Promise and XMLHttpRequest

The following function takes as its argument an object and the object’s name. It then iterates over all the object’s properties and returns a string that lists the property names and their values. dump_props

for…of statement

A function that calls itself is called a recursive function. In some ways, recursion is analogous to a loop. Both execute the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case).

It is possible to convert any recursive algorithm to a non-recursive one, but often the logic is much more complex and doing so requires the use of a stack. In fact, recursion itself uses a stack: the function stack.

You can nest a function within a function. The nested (inner) function is private to its containing (outer) function. It also forms a closure.
A closure is an expression (typically a function) that can have free variables together with an environment that binds those variables (that “closes” the expression).

Using the arguments object
The arguments of a function are maintained in an array-like object. Within a function, you can address the arguments passed to it as follows:

Lexical this 

Until arrow functions, every new function defined its own this value (a new object in case of a constructor, undefined in strict mode function calls, the context object if the function is called as an “object method”, etc.). This proved to be annoying with an object-oriented style of programming.

Alternatively, a bound function could be created so that the proper this value would be passed to the growUp() function.

Arrow functions capture the this value of the enclosing context, so the following code works as expected.

Bitwise logical operators

delete

The delete operator deletes an object, an object’s property, or an element at a specified index in an array. The syntax is:

array, delete vs undefined

The void operator specifies an expression to be evaluated without returning a value. expression is a JavaScript expression to evaluate. The parentheses surrounding the expression are optional, but it is good style to use them.

in

The in operator returns true if the specified property is in the specified object.

Use instanceof when you need to confirm the type of an object at runtime. For example, when catching exceptions, you can branch to different exception-handling code depending on the type of exception thrown

Date in javascript
In the following example, the function JSClock() returns the time in the format of a digital clock.

Using a regular expression literal, which consists of a pattern enclosed between slashes, as follows:

Methods that use regular expressions

When you want to know whether a pattern is found in a string, use the ​test or search ​​method; for more information (but slower execution) use the exec or
match methods.

Advanced searching with flags
Regular expressions have four optional flags that allow for global and case insensitive searching. These flags can be used separately or together in any
order, and are included as part of the regular expression.

foreach
Since JavaScript elements are saved as standard object properties, ​it is not advisable to iterate through JavaScript arrays using for…in loops
because normal elements and all enumerable properties will be listed​​.

array and sort

map​​(callback[, thisObject]) ​returns a new array of the return value from executing callback on every array item​​.
Apply

filter​​(callback[, thisObject]) ​returns a new array containing the items for which callback returned true​​.
Where

reduce​​(callback[, initialValue]) applies ​callback(firstValue, secondValue) to reduce the list of items down to a single value​​.
Group

Map object
ECMAScript 6 introduces a new data structure to map values to values. A Map object is a simple key/value map and can iterate its elements in insertion
order

Use maps ​​over objects when keys are unknown until run time, and when all keys are the same type and all values are the same type.
Use objects ​​when there is logic that operates on individual elements.

One use case of WeakMap objects is to store private data for an object or tohide implementation details.

Set objects are collections of values. You can iterate its elements in insertion order.
A value in a Set may only occur once; it is unique in the Set’s collection.

WeakSet ​​objects are collections of objects. An object in the WeakSet may only occur once; it is unique in the WeakSet’s collection and objects are not
enumerable. The use cases of WeakSet objects are limited. ​They will not leak memory ​​so it can be safe to use DOM elements as a key and mark them
for tracking purposes.

Before ECMAScript 5, there was no native way to list all properties of an object. However, this can be achieved with the following function:

Using the Object.create method

The following illustrates how getters and setters could work for a user­defined object o.

A prototype­based language, such as JavaScript, does not make this distinction: it simply has objects. A prototype­ based language has the notion of a
prototypical object, ​an object used as a template from which to get the initial properties for a new object​​. ​Any object can specify its own
properties, either when you create it or at run time​​. In addition, any object can be associated as the prototype for another object, allowing the second
object to share the first object’s properties.

You can use call to chain constructors for an object, similar to Java.