Category Archives: javascript

How do you consume API in React Native?

https://redux.js.org/api/applymiddleware
https://redux.js.org/api/combinereducers
https://stackoverflow.com/questions/35622588/how-to-reset-the-state-of-a-redux-store
https://react-redux.js.org/using-react-redux/connect-mapstate
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
https://redux.js.org/api/store

We consume data the web API and retrieve data through utility function request. We then pass the data through actions and reducers, which are hooked up to our singleton store. This ensures consistency. We finally use and expose this data in our components.

Intro

We use React Redux to store data into a singleton store.
We do this through createStore, which takes two parameters: reducer and a Thunk Middleware.

The idea is that middleware is the suggested way to extend Redux with custom functionality. middleware lets you wrap the store’s dispatch method for custom use. Multiple middleware can be combined together, where each middleware requires no knowledge of what comes before or after it in the chain.

Thunk as Middleware

The most common use case for middleware is to support asynchronous actions. It does so by letting you dispatch async actions in addition to normal actions. In our case, we use a Redux Think as middleware.

First, a thunk is a subroutine used to inject an additional calculation into another subroutine. In the case of a
Redux Thunk, they are functions that wrap expressions in order to delay their evaluation.

This delay is achieved in when an action is called it returns a function. This function that is returned can then be called at a later time.

Here is an example of a thunk action.

A higher order function is just a function that either
1) returns a function
OR
2) takes a function as one of its arguments.

Because this function returns another function that takes dispatch as an argument this is an example of a higher order function. When called at a later time, it passes in dispatch, which the inner function uses.

Hence, when we apply thunk as middleware, and pass this into createStore to signify that when we execute an action, we can have it be applied to the store asynchronously via higher order functions via Redux Thunk.

rootReducers

Now, the thing you’ll see is the rootReducer.
Basically we use the redux function combineReducers to combine all of our reducers into one.

The combineReducers helper function turns an object whose values are different reducing functions into a single reducing function you can pass to createStore.

The resulting reducer calls every child reducer, and gathers their results into a single state object. The state produced by combineReducers() namespaces the states of each reducer under their keys as passed to combineReducers()

The combineReducers function returns a function. That function is a reducer that invokes every reducer inside the reducers object, and constructs a state object with the same shape.

Resetting the store:

store

Hence, this is what our store code looks like.

1) We import what we need from redux
2) We import our custom reducer cctv
3) We group our reducers into combineReducers
4) Then as long as the action type is not ‘USER_LOGOUT’, then we return the appReducer for standard action onto the store state.
5) We apply think to our middleware
6) Then pass everything into createStore.

src/store.js

Custom Action for CCTV

We first start at the action functions. Action functions are imported into Component classes to be executed at certain points. Say you want to read data from an API during the loading up of the component, you’ll execute an action function in its componentDidLoad. You want to do an action after a button press, you’ll execute that action function in the button press’s handler.

The action function is just a function so that it does an action. Let’s take a look at action getCCTV. You’ll see that it takes a parameter transshipment object. We want to manipulate the store asynchronously so we use thunk’s dispatch function. We do this through a higher order function where we return an object. This object is called at a later time by Redux where it executes our commands asynchronously.

We import the function request. We also define macros.

src/services/api/CCTV/action.js

Then we define functions that return action objects, with type property.

src/services/api/CCTV/action.js

In getCCTV, we take a transhipment object first, then we return a function definition with parameter dispatch. This dispatch is provided by Redux, and in which we use it to do asynchronously manipulation in our function definition.

1) Thus, we first pass an action object to signify that we’re loading. We call dispatch on this action object.

Our reducer will receive this action object, where action.type is CCTV_DATA_IS_LOADING.
Then it would update the store state’s property in need.

2) Then, we request data from the web api by calling request.
When it comes back with the result, we create an action object with the retrieved data and then define type to be CCTV_DATA. We call dispatch to apply this data to the store via the reducer object.

In this case, our action.type is CCTV_DATA, and action.data is Data from the web API retrieval. This is what will be sent to the Reducer.
Our reducer checks action.type. Once it matches, it will take care of processing that action. It updates the store on the action.data provided.

src/services/api/CCTV/action.js

Custom Reducer for CCTV

Basically our reducer receives an action object from the action file.
We then check action.type, it will have a string macro.
For every string macro, we take care of that case by updating the store.

src/services/api/CCTV/reducer.js

The return means it updates the store object, which then will be used by our component.

Component

ref – https://react-redux.js.org/api/connect#connect

So we import the CCTV action and then assign it to prop object’s property getCCTVAction.
But first, let’s talk about the connect function.

The connect() function connects a React component to a Redux store.

It provides its connected component with the pieces of the data it needs from the store, and the functions it can use to dispatch actions to the store.

Hence, we first define CCTVScreen component as so:

src/scenes/App/CCTVScreen/index.js

You’ll see that we pass CCTVScreen into the connect function via currying.

The connect function does not modify the component class passed to it; instead, it returns a new, connected component class that wraps the component you passed in.

where definition of connect is:

mapDispatchToProps

first look at the object for the parameter mapDispatchToProps?
We basically define dispatch actions to our prop object. These are basically functions you can call.

mapStateToProps

Now let’s look at mapStateToProps.

It is defined as so:

So it needs to pass in a property, which we de-structure from the store object. Since we’re working with cctv, we de-structure property “cctv” from the store. This is because cctv is the name of the reducer we used in the combineReducers function.

Remember in our reducer we have property cameras and isCCTVLoading, so we access them through the variable cctv.

Putting it all together

Thus, we put all of this together, which brings us to a connect function that
1) maps state to your props object
2) maps dispatch actions to your props object
3) connects all of that to your component

Using your actions and state

Remember that our cameraViews property in our props object is cctv.cameras.
Hence we extract that property via destructuring.

our cameraViews is cctv.cameras, where cameras is an array of camera data.
Each camera data contains URL to the camera image, and so forth.

Hence, now that we have our cameraViews array, we’ll use Javascript’s map function to iterate through this array and display the information.

As each camera is processed, we display an Image, and give the URL of the image to the key. Thus, this will successfully display the camera image.

double arrow functions (curry + closure)

When working with es6 js, you’ll see arrow functions like this:

Let’s break it down and see what’s happening.

Let’s process from left to right.

We first have a temp variable add that takes on a function with parameter x and a return expression.

Then we see that the return expression is (y) => x + y, which is a function.
Hence, this usage is a curry function. We return a partial function for continual external use.

In our curry function, the y is a parameter.

Hence, we we combine the two, we get:

The es6 way:

Boyer Moore (good suffix heuristic)

source code – https://github.com/redmacdev1988/boyerMoore/blob/master/index.js

The idea of prefix and suffix borders

A border is a substring which is both proper suffix and proper prefix.

For example, in string ‘ccacc’,’cc’ is a border because it appears in both end of string but ‘cca’ is not a border.

In string, ‘cacc’, ‘c’ is a border because it appears in both end of the string. ‘ca’ is not a border.

Let’s look at example where our pattern is aacaa, and an already calculated Suffix Border Index array.

At pattern index 0, we have string aacaa. Its border is aa.
Hence, the prefix border is ‘aa’ at [0][1].
The suffix border is ‘aa’ at [3][4].

We write the beginning index of the suffix border (3) into our border array at index 0.

Thus, for the border array at index 0, we write 3. This means that for the string at pattern index 0, the suffix border starts at index 3.

Let’s move on to pattern index 1. We have string acaa. The prefix border is ‘a’ at index 1. The suffix border ‘a’ at index 4.
Hence, for the border array at index 1, we write 4. This means that for the string at pattern index 1, the suffix border starts at index 4.

At pattern index 2, we have string ‘caa’. There is no border string. Thus, for the value in our border array, we simply write 5, which represents DNE.

At pattern index 3, we have ‘aa’. The prefix border is ‘a’ at pattern index 3. The suffix border is ‘a’ at pattern index 4. This means that for the string at pattern index 3, the suffix border starts at index 4.

Finally, we come to the last character of pattern index 4 ‘a’. It is only 1 character and does not have any border. So we simply assign the length of the pattern to represent DNE.

How to calculate the Suffix Border Index table

1) to start off, we get the length of the pattern. This value will represent DNE for all the pattern substrings that do not have borders.

2) The idea is that we process it going backwards using two indexes i and j.
We simply have i go backwards. For each i iteration, we get index j and process it to check if the character at i and character at j matches.

3) If it matches, we record a suffix border index. If it doesn’t match, we simply assign it as length of the pattern to designate the suffix index DNE.

  • i is index of the pattern substring.
  • j is index of the suffix border.
  • _borderPosition represents an array that contains all suffix border positions

Let’s look at it in detail:

Given pattern ‘aacaa’.

i = 5, j = 6.
border position for 5 is 6, because index 5 does not exist.

0 1 2 3 4 5 (index)
a a c a a X (pattern)
0 0 0 0 0 6 (suffix border index)

We then start going backwards for index i.

i is 5, j is 6

(5 > 0) √
(6 <= 5) X

our j index of 6 is larger than pattern length, so we skip.
decrement i, j to 4, 5.

_borderPosition[4] = 5. This means at pattern index 4, the border index is 5, which denotes DNE. It means the substring at pattern index 4 does not have a border.

0 1 2 3 4 5 (index)
a a c a a X (pattern)
0 0 0 0 5 6 (suffix border index)

i is 4, j is 5

(4 > 0) √
(5 <= 5) √

p[4-1] “a”
p[5-1] “a”

There’s a match so we don’t process index j anymore. We jump out of the loop and decrement i, j to 3, 4.

_borderPosition[3] = 4. This means at pattern index 3, which is substring ‘aa’, the suffix border index is 4.

0 1 2 3 4 5 (index)
a a c a a X (pattern)
0 0 0 4 5 6 (suffix border index)

i is 3, j is 4

(3 > 0) √
(4 <= 5) √

p[3-1] “c”
p[4-1] “a”

There’s no match so we keep processing index j.
We keep processing by going backwards on the _borderPosition array.

j = _borderPosition[4] = 5.

(3 > 0) √
(5 <= 5) √

p[3-1] “c”
p[5-1] “a”

j = _borderPosition[5] = 6.

(3 > 0) √
(6 <= 5) X

skip out of inner while loop
i–; j–; so i is now 2, j is now 5.
_borderPosition[2] = 5.

0 1 2 3 4 5 (index)
a a c a a X (pattern)
0 0 5 4 5 6 (suffix border index)

The substring ‘caa’ at index 2, does not have a suffix border index. So we give is value 5 to denote DNE.

i is 2, j is 5

(2 > 0) √
(5 <= 5) √

Notice j starts over again from the end. The reason we do this is so that we try to find borders. We go back to trying to see if there’s a match for “a”.
if there is, then the current index i has a prefix border.

p[2-1] “a”
p[5-1] “a”

i–;j–‘ 1, 4
_borderPosition[1] = 4;

0 1 2 3 4 5 (index)
a a c a a X (pattern)
0 4 5 4 5 6 (suffix border index)

We then go back one more step to see if there’s additional matches. For every match that happens, we record in the border position of that
match at j.

i is 1, j is 4

(1 > 0) √
(4 <= 5) √

p[1-1] = “a”
p[4-1] = “a”

_borderPosition[0] = 3

0 1 2 3 4 5 (index)
a a c a a X (pattern)
3 4 5 4 5 6 (suffix border index)

Why do we need Suffix borders?

Naive algorithm jumps 1 step at a time. But this is too slow.
Other ways, we jump pattern.length at a time. But we will miss out on potential matches in the middle.

Thus the suffix border array is created so we know where the potential matches are in the middle. WE calculate the suffix border so that we can jump to the correct prefix border for the next potential match.

Setting up the Shift array with Suffix Index Array

So given _borderPositions array as

0 1 2 3 4 5 (index)
a a c a a X (pattern)
3 4 5 4 5 6 (suffix border index)

This means that at index 0 of the pattern, 3 is the index in which the suffix border happens.

Given that if our shift array value is 0, this means it was not assigned.
In this case, we give it the default of the first value of the _borderPositions.

This is so that when we find a match, We know how many steps to skip down. For example, in our case, when a successful search is found, we always skip 3 steps (_shift[0] which is the _borderPosition[0]).

This is so that we can successfully start at the index of the next potential match.

After processing, our shift array looks like this:

0 1 2 3 4 index
3 3 3 3 1 shift

What this means is that while trying match our pattern char to the text char, if for any reason from index 0 to index 3 is a mismatch, we want our i to shift down 3 spaces. This is because 3 spaces down, there is potential for our pattern to match again due to the suffix border.

However, at index 4, if there’s a mismatch, we only shift i down 1. This is because our very first character is a mismatch so we always need to check for the next one. Also, in our shift array, _shift[4+1] is DNE, so we just use default step 1.

If say, our first character at index 4, matches, then index 3 is a mismatch, we shift i down text array 1 steps because _shift[3+1] = 1.

You can see it with an example like this:

0 1 2 3 4 5 6
b a a c a a b (text)
a a c a a (pattern)

we have a mismatch at index 3 because text[3] “c” != pattern[3] “a”.
Hence we take _shift[j+1] = _shift[4] = 1.

After we shift 1, we get

0 1 2 3 4 5 6
b a a c a a b (text)
_ a a c a a (pattern)

match!

The Search

We do the match going backwards:

  • i is the index we’re going to use for every substring of the text
  • j is the index on the pattern. We use this to compare the pattern char to the text char

if the chars at i and j keeps matching, we continue down until j is -1. This means we have matched every character in the pattern matched up in the text.

Thus, when j < 0, we found a pattern match in text. We then log i in order to let the user know where the match happens. Now, we move i down for the next substring to check for a match. So the issue here is, how many steps do we move i down? Typically, we would say, hey why not just shift the i down 5 steps because that's the length of our pattern. We've compared our pattern already, so its safe to go down 5 steps right? The answer is no. What we need to do is shift down 3 steps to the to _shift[0]. This is the 1st of the suffix border index. We need to do this in order to find substring potential matches.

tight vs loose coupling (js)

ref – https://www.reddit.com/r/learnjavascript/comments/30mnra/tight_vs_loose_coupling_examples/

In JS, tight coupling between methods and objects in which if you were to change property name to say naaaaame,
then method sayName will not work.

Change from tight to loose

There is a tight coupling with Food and Fork. Because Fork was instantiated inside nomNomNom, you are forced to use a Fork for every Food.

Let’s correct it by using a parameter object to pass in whatever tool we need to use. This way, we inject whatever tool we need into the eating function.

The only thing we need to make sure is that the tool has a getType function and conforms to a common interface. That way, we can get the name of the tool.

Currying and Partial Functions (js)

ref – https://hackernoon.com/currying-in-js-d9ddc64f162e
https://codeburst.io/currying-in-javascript-ba51eb9778dc
https://blog.bitsrc.io/understanding-currying-in-javascript-ceb2188c339
https://dev.to/damcosset/higher-order-functions-in-javascript-4j8b

Kyle Simpsons – Functional Programming

Arity
Higher Order functions.
Closure

Curry – the process (implementing) of taking in a function with multiple parameters and creating unary (takes in 1 parameter) closures/functions.

Partial App – is applying the params and actually using the app.

Partial Functions

ref – https://medium.com/@JosephJnk/partial-function-application-in-javascript-and-flow-7f3ca87074fe

Partial application is the act of taking a function which takes multiple arguments, and “locking in” some of those arguments, producing a function which takes fewer arguments. For instance, say we have this function:

‘square’ is partial application: we create square by making a new function, which just passes its arguments through to another function, adding some hard-coded arguments to that other function.

Partial application transforms a function into another function with smaller arity.

where arity means the number of arguments a function takes.

Currying

Named after Haskell Brooks Curry, currying is the process of breaking down a function into a series of functions that each take a single argument. In other words, Currying is a technique of evaluating function with multiple arguments, into sequences of function with single argument.

In other words, when a function, instead of taking all arguments at one time, takes argument one and returns a new function. that takes argument two and returns a new function which takes the third one, and so forth, until all arguments have been fulfilled.

That is, when we turn a function call add(1,2,3) into add(1)(2)(3) . By using this technique, the little piece can be configured and reused with ease.

A curried function is a function that takes multiple arguments one at a time. Given a function with 3 parameters, the curried version will take argument one and return a function that takes argument two. It then returns a function that takes the third argument. The last function returns the result of applying the function to all of its arguments.

Why it’s useful ?

Currying helps you to avoid passing the same variable again and again.
It helps to create a higher order function. It’s extremely helpful in event handling.
Little pieces can be configured and reused with ease.

Currying example

Here’s a simple example. We’ll write a function sum3 takes three numbers and returns their sum.

In a standard way, the function is implemented like so:

However, if we provide too few parameters, or too many parameters, then it can have unintended consequences.

add(1,2) –> NaN
add(1,2,3,4) –> 6 //Extra parameters will be ignored.

The curried version of sum3 behaves a differently. It accepts one argument and returns one function. The returned function also accepts one argument and also returns another function that also accepts one argument and …

This cycle continues until the returned function accepts the last argument. The last one in the chain, finally returns the sum.

This works because JS supports closures.

Currying is a transform that makes f(a,b,c) callable as f(a)(b)(c). JavaScript implementations usually both keep the function callable normally and return the partial if arguments count is not enough.

Another example of why currying is useful

Of course, currying comes in handy when you want to:

1. Write little code modules that can be reused and configured with ease, much like what we do with npm:

For example, you own a store🏠 and you want to give 10%💵 discount to your fav customers:

When a fav customer buys a good worth of $500, you give him:

You see that in the long run, we would find ourselves calculating discount with 10% on a daily basis.

We can curry the discount function, so we don’t always add the 0.10 discount:

Now, we can now calculate only with price of the goods bought by your fav customers:

Again, it happens that, some fav customers are more important than some fav customers- let’s call them super-fav customers. And we want to give 20% discount to our super-fav customers.

We use our curried discount function:

We setup a new function for our super-fav customers by calling the curry function discount with a 0.2 value , that is 20%.

The returned function twentyPercentDiscount will be used to calculate discounts for our super-fav customers:

2. Avoid frequently calling a function with the same argument:

For example, we have a function to calculate the volume of a cylinder:

To resolve this, you curry the volume function(like we did earlier):

We can define a specific function for a particular cylinder height:

More Example

How does Curry work?

Currying works by natural closure.The closure created by the nested functions to retain access to each of the arguments.So inner function have access to all arguments.

Additional Examples

ref – https://www.sitepoint.com/currying-in-functional-javascript/

You can see how powerful this approach is, especially if you need to create a lot of very detailed custom functions.
The only problem is the syntax. As you build these curried functions up, you need to keep nesting returned functions,
and call them with new functions that require multiple sets of parentheses, each containing its own isolated argument.
It can get messy.

To address that problem, one approach is to create a quick and dirty currying function that will take
the name of an existing function that was written without all the nested returns.
A currying function would need to pull out the list of arguments for that function,
and use those to return a curried version of the original function:

Currying is an incredibly useful technique from functional JavaScript.
It allows you to generate a library of small, easily configured functions that behave consistently,
are quick to use, and that can be understood when reading your code. Adding currying to your coding practice
will encourage the use of partially applied functions throughout your code, avoiding a lot of potential repetition,
and may help get you into better habits about naming and dealing with function arguments.

Higher Order function

A higher order function is a function that takes a function as an argument, or returns a function.

One of the great advantages of using higher order functions when we can is composition.

We can create smaller functions that only take care of one piece of logic. Then, we compose more complex functions by using different smaller functions.

This technique reduces bugs and makes our code easier to read and understand.

By learning to use higher-order functions, you can start writing better code.

First we see an array of students:

Let’s write functions:

note, interface for reduce:

function(total,currentValue, index,arr) Required.
A function to be run for each element in the array.

Function arguments:

total Required. The initialValue, or the previously returned value of the function
currentValue Required. The value of the current element
index Optional. The array index of the current element
arr Optional. The array object the current element belongs to

Then insert other functions into function average. It helps you get the average of boy’s grades, and girls grades, and everyone’s grades.
Hence as you can see, its composition.

udemy example

Given function ffn that adds three args.

We create a curry function that will will spit back a closure with a function reference in it depending on whether you keep executing the curried function.

It will be used like this:

Let’s break it down.

We start off with

Which dictates the function and the # of args. The # of args will be matched later as each arg is executed during the curry. Hence, take note of arity

Now we create an IIFE that executes right away. This gives prevArgs to whatever is inside. If we decide to return a function that is inside, then that function has access to prevArgs.

Why do we do this? Because we want to get the previous args. Initially, we start off with empty array [].

curried is a function reference, so we need to execute and pass in a parameter. After we pass it in, we will be able to see the full args list.

For example curry(10)(14).

We have empty array to start when we execute curry. Then we return a function reference curried,
curry(10)(14), in which we put 10.

Now, we have

the # of args !== arity yet, so we keep going.
We create another closure with IIFE with the args list. We return a function reference curried,
curry(10)(14), in which we put 14.

Now, we have

so on and so forth…

Finally, when the # of args we input matches that of arity, we execute fn, which is the original function.

Source

functions are first class objects (js)

ref – https://medium.com/front-end-weekly/javascript-functions-are-objects-6affba08ab26
https://hackernoon.com/javascript-and-functional-programming-pt-2-first-class-functions-4437a1aec217

Functions as First-Class Objects in JavaScript: Why Does This Matter?

In computer science, a programming language is said to support first-class functions (or function literal) if it treats functions as first-class objects.

First class objects are entities that can be dynamically created, destroyed, passed to functions, returned as a value, have all the rights as other variables in the language. Same as any other objects. It can have properties, methods.
In other words, this means that JS supports constructing new functions during the execution of a program, storing them in data structures, passing them as arguments to other functions, and returning them as the values of other functions. In other words,

First-class citizenship, within the world of programming, means that a

given entity (such as a function) supports all the operational properties inherent to other entities; properties such as being able to be assigned to a variable, passed around as a function argument, returned from a function, etc.

Basically, first-class citizenship simply means “being able to do what everyone else can do.”

Excellent! But okay… who cares if JavaScript functions are first-class objects? What does it matter?

The beauty of JavaScript functions enjoying first-class citizenship is the flexibility it allows.

Functions as first-class objects

opens the doors to all kinds of programmatic paradigms and techniques that wouldn’t otherwise be possible.

– Functional programming is one of the paradigms that first-class functions allow.

– Additionally, listening for and handling multiple events by passing callback functions is a useful feature within JavaScript and is achieved by passing a function as an argument to the document object’s addEventListener method.

for example, we have a form with id msgbox. It takes text input, and when you press the submit button, it’ll send a “submit” event.

What we try to do, is listening for that event, and get the data from the form.

This is where we pass the SendMessage function as a argument to the addEventListener method.

Where callback functions SendMessage implementation is:

Once we have listened in on the ‘submit’ event, we call SendMessage function in order to create a CustomEvent object with id “newMessage”, stick the user text into it, and then dispatch the event. Now, whoever is listening in on Events with id “newMessage” will be able to receive that event.

So we have a div to put all our text in.

Then we have this div listen for “newMessage” events.
Whenever we get “newMessage” events, we want to call newMessageHandler function.

Now, the callback function newMessageHandler has parameter event e, which is the CustomEvent itself.
Take note that the CustomEvent is of an object with properties details, bubbles, and cancelable.

so in newMessageHandler, we have parameter Event e object. This object is

So in newMessageHandler, we then access the msg via detail property via
e.detail.message

– Furthermore, the practices of closure and partial-application/currying would not be possible within JavaScript if functions didn’t enjoy the status of first-class.

ref – http://chineseruleof8.com/code/index.php/2016/01/05/closures-2/
Closure example

output:

The result is:
0
1
2
3
4
5
6
7
8
9

1 second later…

10
10
10
10
10
10

The reason why is because the for loop does 2 things:

1) print out the i
2) set up an async execution of a function that prints i.

The reason why you get 0-9 in the beginning is due to 1). It prints the i right away.
Then it will set up 10 async execution of the callback function.

Once the 1 second passes, it will run the callback.
The reason why the 10 callback functions will all print out all 10s, is because i is already at 10.

The inner function in the setTimeout references the i via parent scope.

The next thing we can do is execute the function expression via IIFE right away like so:

Now, due to executing the inner function right away, we’ll get the results like so:

for loop: 0
callback: 0 √
for loop: 1
callback: 1 √
for loop: 2
callback: 2 √

When the 1 second passes, it won’t execute the inner function because it was already executed.
The reason why i logs correctly is because we not waiting until it hits 10. We are referencing i right at the moment of the loop, and not after the looping is done.

However, this isn’t exactly what we want.

What we want to do is this. Everytime the for loop sets up an inner function for setTimeout, we know that having the inner function referencing i won’t work because 1 second later, i will already be 10. What we want to do is save the state of the i right at the instant the loop is happening. Hence, what we want to do is:

1) use IIFE to pass in a parameter where we store index i. It will execute this IIFE right away. But since it executes right away, similar to the last example, wouldn’t setTimeOut not be able to execute it?

2) That’s the trick. We return a function to be executed by the setTimeout. 1 second later, the returned function will execute. That function will log index, which has saved state.

output:

for loop: 0
execute inner function: 0 √
for loop: 1
execute inner function: 1 √
for loop: 2
execute inner function: 2 √
for loop: 3
execute inner function: 3 √
for loop: 4
execute inner function: 4 √
for loop: 5
execute inner function: 5 √
for loop: 6
execute inner function: 6 √
for loop: 7
execute inner function: 7 √
for loop: 8
execute inner function: 8 √
for loop: 9
execute inner function: 9 √

1 second later …

execute return function: 0
execute return function: 1
execute return function: 2

In conclusion, due to us being able to return functions as objects, and passing them as parameters, functions as firsts class objects allows closures to happen.

Currying Example

ref – http://chineseruleof8.com/code/index.php/2019/01/05/currying-js/

Function

In JavaScript, functions are objects (hence the designation of first-class object). They inherit from the Object prototype and they can be assigned key:value pairs. These pairs are referred to as properties and can themselves be functions (i.e., methods).

And as mentioned, function objects can be assigned to variables, they can be passed around as arguments; they can even be assigned as the return values of other functions. Therefore, functions in JavaScript are first-class objects.

Additionally, functions are a type of object with two special properties, name and code. A function can be named or anonymous. If it’s named then the name will be stored in name property and the code we want to execute will be stored in code. When we try to invoke a function , JavaScript will try to execute the code segment in the code property.

Since functions are a type of objects, we are able to attach properties to the functions. As you can see in the above image, there are several properties and methods in the “myFunction” function.

We can use the function’s prototype property to store our methods which are common to all objects created using this function. This will help to save all the methods in one place and helps us to reduce the memory footprint of our objects since our methods are stored in the prototype not in the individual objects.

Open up a browser, and open up Elements. Then type in:

When you analyze the instance of a, you’ll see the structure and hierarchy. The black box is the instance. It has a __proto__ property that is red. It points to the prototype object of MyFunction.

Under the prototype property, you’ll see properties constructor and __proto__.
MyFunction’s constructor property points back to MyFunction’s constructor function.
The __proto__ points down to object prototype.

From an Object structure point of view, in Chrome Elements, it looks like this:

Diagram wise, it looks like this:

We then add a property to the instance. As you can see, the property belongs to the instance. Each instance will have its own “nickname” property.

Finally, we add a function to the prototype. This means all instances of MyFunction can share/use this singular function.

  • A function is an instance of the Object type
  • A function can have properties and has a link back to its constructor method
  • You can store the function in a variable
  • You can pass the function as a parameter to another function
  • You can return the function from a function

Having functions as type of object helps us to pass our functions into another functions as arguments and open new possibility of writing good programs. I hope you got little more understanding of functions in JavaScript. If you like the article or have any suggestions on improving my article, please reply to this article or contact me.

Storing a function

Functions can be stored in three ways:

store in a variable :

store in an object :

store in an array :

In the first and third example, I used a named function expression.
The function expression defines a function as part of a larger expression. The line of code doesn’t start with function .

Function as an argument

In the next example, the function doSomething is sent as an argument to doAction().

A callback is a function passed as an argument to another function.

Higher order functions

A higher order function is:
1) a function that takes another function as an input,
2) returns a function or does both.

Let’s look at some built-in methods that are higher-order functions : filter(), map() and reduce().

filter() takes elements out from a list based on a function that decides if the value should be kept.

instance of (js)

ref – https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof

User Object

Create Prototype Object and Connect

Whenever we want a object to derive from other objects, we derive their prototype functionalities.
We do so like this:

1) create the an object X with its property __proto__ pointing to the prototype object via Object.create.
2) have their function constructor’s prototype point to that object X.
3) have the object X’s constructor point back to the constructor function
4) Now that we are done connecting, we can use a callback to execute any prototype implementations.

Admin and SuperAdmin

Create the Admin constructor function, initialize its subclass, and then initiate its own property.
Since we want to derive from the user prototype, we put in Admin as the constructor, User.prototype as the prototype object we want to derive from, and finally, implement the prototype functionalities.

instanceof

The instanceof operator tests whether the prototype property of the [Constructor function] appears anywhere in the prototype chain of the [object].

instanceof is an operator and it expects two operands:

– an object
– Constructor function

it will test if the passed function prototype property exists on the chain of the object.

For example:

Diagram wise:

Hence, as we can see, for object u,

the prototype property of Admin appears in the prototype chain.
the prototype property of User appears in the prototype chain.
However, the prototype property of SuperUser DOES NOT appear

isPrototypeOf

the 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.

for example…

static functions used with prototype functions (js)

ref – https://stackoverflow.com/questions/1635116/javascript-class-method-vs-class-prototype-method

Yes, the first function has no relationship with an object instance of that constructor function, you can consider it like a ‘static method’.

In JavaScript functions are first-class objects, that means you can treat them just like any object, in this case, you are only adding a property to the function object.

The second function, as you are extending the constructor function prototype, it will be available to all the object instances created with the new keyword, and the context within that function (the this keyword) will refer to the actual object instance where you call it.

When MyClass.prototype.publicMethod can access ‘privileged’ members, it means you can access privileged properties and functions from constructor function.

When MyClass.prototype.publicMethod can access ‘public’ members, it means you can access public functions from the prototype, like so:

privacy in IIFE vs Prototypes

Prototypes

In prototypes, we use function constructors to initiate.

Then we use prototypes to create one copy of functions to be shared by all instances of HashTable.

IIFE

If you want privacy, use IFEE and closure.

Declared and undeclared variables in functions

ref – https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var

Declared variables are constrained in the execution context in which they are declared.

Undeclared variables are always global

…even in inner functions

Let’s declare an inner function called ‘inner’. We have an undeclared variable ‘name’.
That name will be declared as a global. It will be accessible by all scopes.