Categories
JavaScript

What are Rxjs Subscriptions?

A Subscription in RxJS is a disposable resource that usually represents the execution of an Observable. It has the unsubscribe method which lets us dispose of the resource held by the subscription when we’re done.

It’s also called ‘Disposable’ in earlier versions of RxJS.

Basic Usage

A basic example of a subscription can be seen in the following code:

import { of } from "rxjs";
const observable = of(1, 2, 3);  
const subscription = observable.subscribe(val => console.log(val));  
subscription.unsubscribe();

In the code above, the subscription returned when we call subscribe on an Observable is a subscription. It has the unsubscribe method, which we called on the last line to clean up when the Observable is unsubscribed.

Combining Subscriptions

We can combine subscriptions with the add method that comes with Subscription objects.

For example, if we have 2 Observables:

import { of } from "rxjs";
const observable1 = of(1, 2, 3);  
const observable2 = of(4, 5, 6);
const subscription1 = observable1.subscribe(val => console.log(val));
const subscription2 = observable2.subscribe(val => console.log(val));
subscription1.add(subscription2);

In the code above, we have 2 Subscriptions, subscription1 and subscription2, which we joined together with the add method of subscription1.

subscription1 is a parent of subscription2.

We should get

1  
2  
3  
4  
5  
6

as the output.

When we join Subscriptions together, we can unsubscribe to all the Subscriptions that were joined together by calling unsubscribe on the first Subscription that the add method is called on.

For example, if we have:

import { interval } from "rxjs";
const observable1 = interval(400);  
const observable2 = interval(300);
const subscription = observable1.subscribe(x => console.log(x));  
const childSubscription = observable2.subscribe(x => console.log(x));
subscription.add(childSubscription);

Then calling unsubscribe on subscription will unsubscribe from all the subscriptions that are joined together.

setTimeout(() => {  
  subscription.unsubscribe();  
}, 1000);

Undoing Child Subscriptions

We can undo child subscriptions by using the Subscription’s remove method. It takes a child Subscription as the argument.

To use it, we can write something like the following code:

import { interval } from "rxjs";

const observable1 = interval(400);  
const observable2 = interval(300);
const subscription = observable1.subscribe(x => console.log(x));  
const childSubscription = observable2.subscribe(x => console.log(x));

subscription.add(childSubscription);

(async () => {  
  await new Promise(resolve => {  
    setTimeout(() => {  
      subscription.remove(childSubscription);  
      resolve();  
    }, 600);  
  }); 

  await new Promise(resolve => {  
    setTimeout(() => {  
      subscription.unsubscribe();  
      childSubscription.unsubscribe();  
      resolve();  
    }, 1200);  
  });  
})();

Once the childSubscription is removed, it’s no longer a child of the subscription Subscription.

Therefore, we’ve to call unsubscribe on both subscriptions separately so that we clean up both subscriptions once we’re done.

Subscriptions let us get the values emitted from an Observable. We can join multiple Subscriptions together with the add method, which takes a child Subscription as its argument.

When they’re joined together, we can unsubscribe to them together.

We can remove a Subscription as a child of another Subscription with the remove method.

Categories
JavaScript JavaScript Basics

What are Higher-Order Functions in JavaScript?

In JavaScript, higher-order functions are used in many places. Therefore, it’s important to know what they are.

In this article, we’ll look at what higher-order functions are and how to use them in JavaScript.

Definition of Higher-Order Functions

Higher-order functions are functions that take other functions as arguments or return functions as their results. A function that’s accepted as an argument is also called a callback function.

Why can functions accept other functions as arguments or return functions? This is because JavaScript functions are objects like any other entity in JavaScript. Functions that are objects are called first-class functions.

First-class functions are treated like any other variables. In JavaScript, this is the case, so JavaScript functions are first-class functions.

In JavaScript, we can assign functions to variables:

let foo = () => 1;

In the code above, we assigned a simple anonymous function to the foo variable.

Then we can call it by running:

foo();

We can also add properties to it as follows:

foo.bar = 1;

The code above is bad practice because it’s confusing since functions are usually called rather than manipulated by adding properties to them.

However, we know from this that JavaScript functions are objects. It also has a prototype with methods like apply, bind, and call to modify the behavior of regular functions declared with the function keyword.

Everything that we want to do with other variables like numbers, strings, and objects, we can do with functions.

Functions as Function Parameters

Because JavaScript functions are just regular objects, we can pass them in as arguments when we call a function. This is used in many places like array functions and promise callbacks.

A simple example would be the following:

const addOrMultiply = (addFn, multiplyFn, a, b) => {  
  if (Math.random() > 0.5) {  
    return addFn(a, b);  
  }  
  return multiplyFn(a, b);  
}

const add = (a, b) => a + b;  
const multiply = (a, b) => a * b;  
const result = addOrMultiply(add, multiply, 1, 2);

In the code above, we defined the addOrMultiply function which takes a function to add 2 numbers, function to multiply 2 numbers, and 2 numbers as arguments.

In the function, if Math.random() returns a number bigger than 0.5, then we call addFn(a, b) . Otherwise, we call multiplyFn(a, b) .

Then we defined the add and multiply functions to add and multiply 2 numbers respectively.

Finally, we call the addOrMultiply function by passing inadd and multiply functions and numbers 1 and 2.

This way, the functions we pass in get called with a and b . This doesn’t mean that the function we pass in have to match the signature of the function calls inside the addOrMultiply function. JavaScript doesn’t care about the signatures of the function we pass in. However, we’ve to pass in functions that get us the expected results.

By the definition that we mentioned for higher-order function, addOrMultiply fits the definition of it.

Examples of Higher-Order Functions

Array.prototype.forEach

We can use the forEach method to loop through each element of an array. It takes a callback function as an argument. The callback takes the array entry currently being processed, index of the array being processed, and the array itself as the parameter.

The index and the array parameters are optional. However, we know that JavaScript doesn’t care about the function signature of functions we use for callbacks, so we’ve to be careful.

We can write the following code:

const arr = [1, 2, 3];  
arr.forEach((a, i) => console.log(`arr[${i}] is ${a}`))

We should see:

arr[0] is 1  
arr[1] is 2  
arr[2] is 3

logged from the console.log .

Array.prototype.map

The map array method takes the same callback function as forEach . It’s used for mapping array entries of the array it’s called on to values returned by manipulating each entry with the callback function. It returns a new array.

For example, we can use is as follows:

const arr = [1, 2, 3];  
arr.map((a, i) => a**2)

Then we should get:

[1, 4, 9]

setTimeout

The setTimeout function delays the execution of the code inside the callback function that we pass into it by a specified amount of time.

For example, we can use it as follows:

setTimeout(() => {  
  console.log('hi');  
}, 1000)

The code above will log 'hi' 1 second after the setTimeout function is called.

setTimeout defers the code inside the callback to the next event loop iteration so that we delay the execution of the code in the callback without holding up the whole program.

This kind of delayed code is asynchronous. We delay code execution without holding up the main execution thread to wait for its execution to finish.

This pattern is common to lots of asynchronous code, including callbacks for promises, event listeners and other pieces of asynchronous code.

Since we can’t execute asynchronous code line by line, callbacks are even more important since it’s the only way to run a function in an indeterminate amount of time.

Event Handlers

Event handlers for DOM elements and in Node.js also use callbacks since there’s code that is only called when an event is triggered.

For example, we can attach a simple click listener to the document object as follows:

document.addEventListener('click', () => {  
  console.log('clicked');  
})

Then whenever we click on the page, we’ll get 'clicked' logged.

As we can see higher-order functions are very useful in JavaScript. It lets us create callback functions to pass into other functions. It’s widely used by synchronous code and asynchronous code alike.

Synchronous callbacks examples include callbacks that we pass into array methods.

Asynchronous callbacks include event handlers, setTimeout , promise callbacks and more. It’s widely used with asynchronous code since the code isn’t run line by line, so we need callbacks to run code that needs to be run in an indeterminate amount of time.

Categories
JavaScript

Using Rxjs Join Creation Operators to Combine Observer Data

RxJS is a library for reactive programming. Creation operators are useful for generating data from various data sources to be subscribed to by Observers.

In this article, we’ll look at some join creation operators to combine data from multiple Observables into one Observable. We’ll look at the combineLatest, concat, and forkJoin operators.

combineLatest

We can use the combineLatest to combine multiple Observables into one with values that are calculated from the latest values of each of its input Observables.

It takes 2 or more Observables as arguments or one array of Observable as an argument. It returns an Observable that emits values that are an array of values of all the Observables that were passed in.

combineLatest also takes an optional project function, which takes an argument of all values that would be normally be emitted by the resulting Observable, then we can return what we want given the values in that function.

combineLatest works by subscribing to each Observablke in order and whenever an Observable emits, collect the emitted data into an array of the most recent values of each Observable. Then the array of values gets emitted by the returned Observable.

To ensure that the output array always has the same length, combineLastest wait for all input Observables to emit at least once before it starts emitting results. If some Observable emits values before others do, then those values will be lost.

If some Obsetrvables doesn’t emit by completes, then the returned Observable will complete without emitting anything since that one didn’t emit any value.

If at least one Observable was passed into combineLatest and all of them emitted something, then the returned Observable will complete when all the combined streams complete. In this case, the value will always be the last emitted value for the Observables that completed earlier.

For example, we can use it as follows:

import { combineLatest, of } from "rxjs";
const observable1 = of(1, 2, 3);  
const observable2 = of(4, 5, 6);  
const combined = combineLatest(observable1, observable2);  
combined.subscribe(value => console.log(value));

Then we get:

[3, 4]  
[3, 5]  
[3, 6]

since observable1 emitted all its values before observable2 did.

We can also use the optional second argument to do some calculations:

import { combineLatest, of } from "rxjs";  
import { map } from "rxjs/operators";
const observable1 = of(1, 2, 3);  
const observable2 = of(4, 5, 6);  
const combined = combineLatest(observable1, observable2).pipe(  
  map(([a, b]) => a + b)  
);  
combined.subscribe(value => console.log(value));

In the code above, we got the sum of the values. Then we get:

7  
8  
9

These are the sum of each entry that we have before.

concat

We can use the concat operator to take multiple Observables and return a new Observable that sequentially emits values from each Observable that were passed in.

It works by subscribing to them one at a time and merging the results in the output Observable. We can pass in an array of Observables or put them directly as arguments. Passing in an empty array will result in an Observable that completes immediately.

concat doesn’t affect Observables in any way. When an Observable completes, it’ll subscribe to the next one an emit its values. This will be repeated until the operator runs out of Observables.

merge operator would output values from Observables concurrently.

If some input Observable never completes, concat will also never complete and Observables follows them will never be subscribed. If some Observable completes without emitting any values, then it’ll be invisible to concat .

If any Observable in the chain emit errors, then the error will error immediately. Observable that would be subscribed after the one that errors will never be subscribed to.

We can pass in the same Observable subscribe to the same one repeatedly.

For example, we can use it as follows:

import { concat, of } from "rxjs";
const observable1 = of(1, 2, 3);  
const observable2 = of(4, 5, 6);  
const concatted = concat(observable1, observable2);  
concatted.subscribe(value => console.log(value));

Then we get:

1  
2  
3  
4  
5  
6

as we expect.

forkJoin

forkJoin accepts an array of Observables and emits an array of values in the exact same order as the passed array or a dictionary of values in the same shape as the passed dictionary.

The returned Observable will emit the last values emitted of each Observable. For example, we can write:

import { forkJoin, of } from "rxjs";
const observable1 = of(1, 2, 3);  
const observable2 = of(4, 5, 6);  
const joined = forkJoin(observable1, observable2);  
joined.subscribe(value => console.log(value));

Then we get [3, 6] .

We can also pass in an object with Observables as properties:

import { forkJoin, of } from "rxjs";
const observable1 = of(1, 2, 3);  
const observable2 = of(4, 5, 6);  
const joined = forkJoin({ observable1, observable2 });  
joined.subscribe(value => console.log(value));

Then we get:

{observable1: 3, observable2: 6}

Conclusion

The combineLatest, concat, and forkJoin operators are very useful for combining emitted data from multiple Observables.

With combineLatest, we can combine emitted data from multiple Observables and get arrays of values that are formed by the latest values emitted by each Observable that we passed in.

The concat operator subscribes to each Observable that we passed in sequentially and return an Observable that emits values from each sequentially. If an error occurs in any Observable, an error will be emitted by the returned Observable.

Finally, the forkJoin operator returns an Observable that get the latest values from each Observable and emits the value as an object or an array depending if you passed in a dictionary of Observables or an array of Observables.

Categories
JavaScript JavaScript Basics

What Does the Percent Sign Mean in JavaScript?

JavaScript has many operators. One of them is the percent sign: %. It has a special meaning in JavaScript: it’s the remainder operator. It obtains the remainder between two numbers.

This is different from languages like Java, where % is the modulo operator.

In this piece, we’ll look at the difference between the modulo and the remainder operator.


Modulo Operator

The modulo operator works like the mod operator in math. It’s a basic part of modular arithmetic, which works like the clock. The number wraps around to something smaller than the given value, when it’s bigger than it.

For example, a clock has 12 hours. We represent that in math with by writing x mod 12 where x is an integer. For example if x is 20 then 20 mod 12 is 8 since we subtract 12 until it’s between 0 and 11.

Another example would be a negative number for x. If x is -1, then -1 mod 12 is 11 since we add 12 to it to make it within between 0 and 11.

12 mod 12 is 0 since we subtract 12 from it until it’s within the same range.

The operand after the mod can be positive or negative.

If the right-hand operand is negative, then the range of it must be from the negative number plus 1 to 0.

For example, if we have 1 mod -3 . Then we subtract 3 from it to get -2 .

To see more properties of modular arithmetic, check out this article for modular arithmetic and this article for the modulo operator from Wikipedia.

The JavaScript percent sign doesn’t do modular arithmetic. It’s used for finding the remainder when the first operand is divided by the second operand.


Remainder Operator

This is what JavaScript’s percent sign actually means. For example, if we write:

10 % 2

we get 0 since 10 is evenly divisible by 2.

If the first operand isn’t even divisible by the second operand, then we get a non-zero remainder. For example, if we have:

10 % 3

Then we get 1 since 10 divided by 3 has a remainder of 1.

Since the percent sign is a remainder operator, it also works if either number is negative. For example, if we have:

10 % -3

Then we get 1 because the quotient is -3 and the remainder is 1.

On the other hand, if we write:

-10 % 3

Then we get -1 because the quotient is -3 and the remainder is -1.


Bitwise Operator for Doing Modular Arithmetic

We can use the >>> operator, which is the zero left shift operator, to compute a number modulo 2 to the 32nd power.

The zero left shift operator shifts right by pushing zero in from the left and the rightmost one falls off the shift.

For example, if we write:

2**32 >>> 32

Then we get 0 since we pushed 32 zeroes in from the left, which pushed all the ones out.

Writing 2**32 >>> 0 is the same as 2**32 >>> 32.

If we write 2**32 + 1 >>> 32 then we get 1 since we added the 33rd bit on the left with the value 1, then we pushed in 32 zeroes from the left, leaving only 1 bit left.


Using Typed Array for Modulo Operation

We can also use typed arrays like the Uint8Array, Uint16Array, and Uint32Array for modulo operations since each entry can only be 0 to 2**8–1, 0 to 2**16–1, or 0 to 2**32–1respectively. The U in the first character of the name means unsigned.

In each example below, we create a typed array with one entry, then we assign various values to it to compute x mod 2**8 , x mod 2**16 and x mod 2**32 respectively.

For example, if we write:

const arr1 = new Uint8Array(1);  
arr1[0] = 2**8;  
console.log(arr1[0]);  
arr1[0] = 2**8 + 1;  
console.log(arr1[0]);

Then we get that the first console.log gives us 0 and the second console.log gives us 1 since the entries are wrapped to be between 0 and 2**8 - 1.

Likewise, we can do the same thing with the other kinds of typed arrays as follows:

const arr1 = new Uint16Array(1);  
arr1[0] = 2**16;  
console.log(arr1[0]);  
arr1[0] = 2**16 + 1;  
console.log(arr1[0]);

And:

const arr1 = new Uint32Array(1);  
arr1[0] = 2**32;  
console.log(arr1[0]);  
arr1[0] = 2**32 + 1;  
console.log(arr1[0]);

Then we get the same results as the first example.


Write a Modulo Function with JavaScript

If we actually want to do modular arithmetic with JavaScript, we have to write our own modulo function.

One example would be this:

const mod = (a, b) => ((a % b) + b) % b

It wraps the results of a % b to be within 0 and b — 1 or b+1 and 0 if b is negative by adding a % b to b. a % b is always less than a since it’s the remainder, but it might not be within the range of 0 and b — 1 or b+1 and 0and 0 if b is negative so we add b to it.

If we write:

console.log(mod(1, 12));  
console.log(mod(13, 12));  
console.log(mod(13, -12));

Then we should get:

1  
1  
-11

This is what we expect.

In JavaScript, the percent sign is the remainder operator. It gets us the remainder of the number when we divide the left operand by the right operand. To do real modulo operations with JavaScript, we have to write our own function to do it or we can use a typed array to do it since it wraps the value to be within the given range.

Categories
JavaScript

What can we build with JavaScript?

From its simple beginnings as a language to do browser-side scripting, JavaScript has evolved a lot since the first version of the language. There’re now lots of things that we can build with JavaScript that we can’t do before. Here’re some things that we can build with JavaScript today.

Client-Side Apps

JavaScript is still the only language for browser-side web applications. The proliferation of app frameworks like React, Angular, and Vue have made things infinitely easier. Also with ES6+, building client-side apps with JavaScript has been much more pleasant than before. Any other language like TypeScript has to be converted to plain JavaScript before they can run in browsers. All modern browsers support JavaScript and nothing else, so it’s the only language for client-side applications.

Server-Side Web Apps

With Node.js, JavaScript has arrived on the server-side. We can do so much with Node.js, like building a back-end app. There’re various back end frameworks like Express, Nest.js, and many other frameworks that let us write back end apps with ease. It’s so popular that popular hosts like Amazon Web Services have provided SDKs for Node.js, so we can integrate with their services without a hitch. It’s also pretty fast and easy to build back end apps with it.

There’re libraries for interacting with most popular database systems like MySQL and Postgres so we can easily use it for back end apps. If we want NoSQL, there’s also tight MongoDB integration with libraries like Mongoose which lets us interact with MongoDB and provides a schema to save dynamic data.

Presentations

With Reveal.js and Eagle.js, we can use it easily to build presentations with HTML, CSS, and JavaScript. It provides as much flexibility as PowerPoint but they cost nothing. This is great since it hasn’t been to easy to build presentations with code before these libraries existed.

Scripts

Once again, Node.js provides a great run-time environment for running scripts. With the fs module, we can do lots of common file and folder operations like add, changing, renaming, and deleting files. Also, changing permissions is easy with it. It also has the child_process module to run processes on any computer the script is running.

Also, Node.js is aware of the differences between Windows and Unix-like systems like Linux and Mac OS, so compatibility issues are minimal when running scripts on any computer.

Games

With HTML5, add interactivity to web pages is easier than ever. This is coupled with the power of JavaScript to make everything dynamic. The Canvas API has lots of methods to draw whatever we want and make them animate.

There’re also game frameworks like Phaser which abstracts out some of the more tedious parts like handling inputs and animations of shapes by abstracting things out into a framework.

Mobile Apps

There’re 2 ways to build mobile apps with JavaScript. One is to write a native app with frameworks like React Native, and the other is to write a hybrid with frameworks like Ionic.

React Native lets us write our app’s code in JavaScript and then compile it into a native mobile app by converting the JavaScript React components into native components of the platforms you’re targeting. Since the framework builds code into native apps, accessing hardware is easier to React Native. It provides built-in support for cameras and accelerometers for example.

Hybrid app frameworks like Ionic let us write apps with HTML, CSS, and JavaScript and then display the code in a browser web view on our mobile devices. Accessing hardware requires native plugins which makes development and testing more difficult. Native plugins are also limited or buggy which is another problem if we try to build apps that need to access hardware with it.

They’re both cross-platform frameworks that let us write our code once and then build them for different platforms.

Internet of Things Programs

We can use JavaScript to build programs that control embedded hardware with frameworks like the Johnny-Five framework. It supports the Arduino single-board computer which we normal load C programs with it.

With Johnny-Five, we can use JavaScript to write our programs which makes writing useful programs a lot easier. It supports full hardware access like LEDs, timers, GPS, motors, buttons and switches, compasses, and more. Of course, this is also thanks to the existence of Node.js since it lets us run JavaScript programs outside the browser.

Desktop Apps

With Electron, we can write desktop apps with JavaScript easily. We can convert React, Angular or Vue apps into Windows, Linux, or Mac OS apps with Electron libraries for these frameworks.

We can also write apps with just the Electron framework alone. It can access things like our computer’s file system so it can do things that a normal desktop program does. However, access to specialized hardware is lacking so it’s more for general business apps. Lots of programs are built with Electron, with the biggest examples being Slack, Visual Studio Code, and the Atom text editor.

We can do a lot with JavaScript. Thanks to Node.js, JavaScript can leave the browser, letting us build apps for Internet of Things devices, back end apps, desktop apps and more. On the browser side, we can use it to build interactive apps like games and rich business apps. We can also make great presentations with it.