Categories
JavaScript JavaScript Basics

Append Item to a JavaScript Array

Appending an item to an array in JavaScript is easy. There’re 2 ways to do it. Either we can use the spread operator, or we can use the array instance’s push method.

To use the spread operator, we can take the original array, spread it into a new array and put the new item at the end, and then we assign it back to the original array.

For instance, we can do that as follows:

let arr = [1, 2, 3];
arr = [...arr, 4];

In the code above, we declare the array with let so that we can do the assignment after it.

Then we append the new array entry to it by using the spread operator and then add the new entry as we did in the 2nd line and assign it back to the original array.

Now arr is [1, 2, 3, 4].

The other way is to call the push method which appends the array item in place.

To do that, we can write:

const arr = [1, 2, 3];
arr.push(4);

Now we have the same result, but we don’t have to assign the modified array back to the original array as we did with the first example, so we can use const to declare the array.

Appending an item to an array is easy with JavaScript.

Categories
JavaScript

Introduction to the JS Destructuring Syntax

The JavaScript destructuring syntax lets us set object property values and array entries as variables without doing that ourselves explicitly.

Arrays

We can destructure arrays by defining the variables on the left side and assigning an array on the right side so that the variables on the left side will be assigned the array entries as values on the right side.

The number of variables on the left side don’t need to match the number of arrays entries on the right side.

Also, we can skip values that we don’t want to assign by putting in nothing or spaces between the commas. For instance, we can destructure an array into variables as follows:

const [one, two] = [1, 2, 3];

In the code above, we defined one and two on the left side, and have 1 and 2 as the first 2 entries of the array on the right side.

So, 1 is assigned to one and 2 is assigned to two.

If we want to only assign 3 to a variable, we can write:

const [, , three] = [1, 2, 3];

Then we would get 3 assigned to three since we skipped the first 2 entries on the left side.

Also, we can assign default values to the variables on the left side, which will be assigned if nothing’s assigned to it.

For instance, we can add one as follows:

const [, , foo = 5] = [1, 2];

In the code above, we defined the foo variable and assigned 5 as the default value for it. Since we don’t have a 3rd entry in the array on the right. foo will keep its default value 5.

Objects

We can also destructure objects property values into variables using the destructuring syntax.

It assigns the value of the property with the same name as the variable name. The nesting level is also matched.

For instance, we can use the destructuring assignment with objects as follows:

const {
  foo: {
    bar
  }
} = {
  foo: {
    bar: 1
  }
}

The code above will assign foo.bar on the right side to bar on the left side since the location and name are the same.

Therefore, bar will be 1.

Like with arrays, we can assign a default value to the variable on the left side.

For instance, we can write:

const {
  foo: {
    bar = 1
  }
} = {
  foo: {}
}

In the code above, we have the default value of bar set to 1. Since the object on the right has an empty object set as the value of foo, we get that bar is 1 since there’s no value assigned to bar.

Function Arguments

We can use the destructuring syntax on function arguments.

For instance, we can write:

const name = ({
  firstName,
  lastName
}) => `${firstName} ${lastName}`

to let our name function take an object with the firstName and lastName properties. Then we can call it as follows:

name({
  firstName: 'jane',
  lastName: 'smith'
})

and we’ll get 'jane smith' returned since the firstName and lastName properties are destructured into variables in the argument.

Loops

We can decompose array entries into variables in loops if we use the for...of loop.

For instance, given the following array:

const arr = [{
    firstName: 'jane',
    lastName: 'smith'
  },
  {
    firstName: 'john',
    lastName: 'smith'
  },
]

Then we can get the firstName and lastName properties from each entry in the for...of loop as follows via destructuring:

for (const {
    firstName,
    lastName
  } of arr) {
  console.log(`${firstName} ${lastName}`)
}

Then the console will log:

jane smith
john smith

Conclusion

The JavaScript destructuring syntax is one of the best features of JavaScript that has been released in the last few years. It makes code cleaner and easier to read while saving typing.

Categories
JavaScript JavaScript Basics

Add a Timer to Run Code Between Specified Time Intervals With JavaScript

Adding a timer is easy with JavaScript. There’re 2 methods for adding a timer into our JavaScript app. One is the setTimeout function. The other is the setInterval function.

Thr setInterval function lets us run code after a given delay in milliseconds repeatedly. It’s queued to be run after the given amount of delay time and then it’ll run the callback we pass in into the main thread.

For instance, we can use it as follows:

setInterval(() => console.log('hi'), 1000);

In the code above, we passed in a callback function as the first argument of the time setInterval function and a 1000 ms interval as the second argument.

Then we should see 'hi' logged in the console log output after every second.

We can also pass in arguments to the callback by passing in more arguments after the second argument. They can be accessed in the callback in the same order.

For instance, we can do that as follows:

setInterval((greeting) => console.log(greeting), 1000, 'hi');

In the code above, we passed 'hi' as the 3rd argument of setInterval, which will let us access the argument from the greeting parameter.

Therefore, we’ll see 'hi' logged in the console log output since greeting is 'hi'.

setInterval also takes a string instead of a callback as the first argument, where the string has the code that a callback normally has.

However, this prevents performance optimizations from being done and also presents security issues since attackers can potentially inject their own code as a string into the setInterval if we aren’t careful.

If we don’t need the timer any more, we can cancel the timer by calling the clearInterval function which takes the timer ID object that’s returned by setInterval.

For instance, we can do that as follows:

const timer = setInterval((greeting) => console.log(greeting), 1000, 'hi');
clearInterval(timer);

Since we called clearInterval immediately after calling setInterval, the callback won’t be called since we disposed of our timer with clearInterval.

Categories
JavaScript JavaScript Basics

Add a Timer With JavaScript

Adding a timer is easy with JavaScript. There’re 2 methods for adding a timer into our JavaScript app. One is the setTimeout function. The other is the setInterval function.

Thr setTimeout function lets us run code after a given delay in milliseconds. It’s queue to be run after the given amount of delay time and then it’ll run the callback we pass in into the main thread.

For instance, we can use it as follows:

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

In the code above, we passed in a callback function as the first argument of the time setTimeout function and a 1000 ms delay as the second argument.

Then we should see 'hi' logged in the console log output after 1 second.

We can also pass in arguments to the callback by passing in more arguments after the second argument. They can be accessed in the callback in the same order.

For instance, we can do that as follows:

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

In the code above, we passed 'hi' as the 3rd argument of setTimeout, which will let us access the argument from the greeting parameter.

Therefore, we’ll see 'hi' logged in the console log output since greeting is 'hi'.

setTimeout also takes a string instead of a callback as the first argument, where the string has the code that a callback normally has.

However, this prevents performance optimizations from being done and also presents security issues since attackers can potentially inject their own code as a string into the setTimeout if we aren’t careful.

If we don’t need the timer any more, we can cancel the timer by calling the clearTimeout function which takes the timer ID object that’s returned by setTimeout.

For instance, we can do that as follows:

const timer = setTimeout((greeting) => console.log(greeting), 1000, 'hi');
clearTimeout(timer);

Since we called clearTimeout immediately after calling setTimeout, the callback won’t be called since we disposed of our timer with clearTimeout.

Categories
JavaScript Rxjs

Rxjs Filtering Operators — Skip and Take

Rxjs is a library for doing 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 more filtering operators, including skipUntil, skipWhile, take, takeLast, takeUntil, and takeWhile operators.

skipUntil

The skipUntil operator returns an Observable that skips items emitted by the source Observable until a second Observable emits an item.

It takes one argument, which is the notifer Observable. When this emits an item, then the source Observable’s emitted values will be emitted by the skipUntil operator.

For example, we can use it as follows:

import { interval } from "rxjs";  
import { skipUntil, take } from "rxjs/operators";

const numbers = interval(1000).pipe(  
  take(10),  
  skipUntil(interval(5000).pipe(take(1)))  
);  
numbers.subscribe(x => console.log(x));

The code above takes the emitted values from the interval(1000) Observabkem then pipe it to the take(10) operator to take the first 10 values, then take those values to the skipUntil operator, which has the interval(5000).pipe(take(1)) Observable passed in.

interval(5000).pipe(take(1)) emits a value after 5 seconds, which then will trigger the emission of the interval(1000) Observable’s emitted values.

Then we should see:

4  
5  
6  
7  
8  
9

skipWhile

The skipWhile operator returns an Observable that skips all items emitted by the source Observable until the condition returned by the predicate function becomes false.

It takes one argument, which is a predicate function to test each item with the condition returned by the function.

For example, we can write the following:

import { of } from "rxjs";  
import { skipWhile } from "rxjs/operators";

const numbers = of(1, 2, 3, 4, 5, 6).pipe(skipWhile(x => x < 3));  
numbers.subscribe(x => console.log(x));

Then the items from the of(1, 2, 3, 4, 5, 6) Observable won’t be emitted when the value is less than 3. This means that numbers will emit 3, 4, 5 and 6.

Once the condition in the predicate function is tested false once, it’ll keep emitting regardless whether the emitted value from the source Observable make the condition evaluate to false or not.

So if we have:

import { of } from "rxjs";  
import { skipWhile } from "rxjs/operators";

const numbers = of(1, 2, 3, 4, 3, 2).pipe(skipWhile(x => x < 3));  
numbers.subscribe(x => console.log(x));

Then we get 3, 4, 5 and 2 since the condition becomes false once the first 3 was emitted by of(1, 2, 3, 4, 3, 2).

take

The take operator returns an Observable that emits the first count values emitted by the source Observable.

It takes one argument which is the count, which the maximum number of values to emit.

For example, we can use it as follows:

import { of } from "rxjs";  
import { take } from "rxjs/operators";

const numbers = of(1, 2, 3, 4, 3, 2).pipe(take(2));  
numbers.subscribe(x => console.log(x));

Then we get 1 and 2 logged since we passed 2 into the take operator.

takeLast

The takeLast operator returns an Observable that emits the last count values emitted by the source Observable.

It takes one argument which is the count, which the maximum number of values to emit from the end of the sequence of values.

For instance, we can use it as follows:

import { of } from "rxjs";  
import { takeLast } from "rxjs/operators";

const numbers = of(1, 2, 3, 4, 5, 6).pipe(takeLast(2));  
numbers.subscribe(x => console.log(x));

We should get 5 and 6 since we passed in 2 to the takeLast operator, which means we only want the last 2 values from the of(1, 2, 3, 4, 5, 6) Observable emitted.

takeUntil

The takeUntil operator returns an Observable that emits value from the source Observable until the notifier Observable emits a value.

It takes one argument, which is the notifier whose emitted value will cause the return Observable to stop emitting values from the source Observable.

For example, we can use it as follows:

import { interval, timer } from "rxjs";  
import { takeUntil } from "rxjs/operators";

const source = interval(1000);  
const result = source.pipe(takeUntil(timer(5000)));  
result.subscribe(x => console.log(x));

The code above will emit the values from the source Observable until timer(5000) emits its first value.

So we should get something like:

0  
1  
2  
3

takeWhile

The takeWhile operator returns an Observable that emits the values emitted by the source Observable as long as the condition in the predicate function is satisfied and completes as soon as the condition is not satisfied.

It takes of argument, which is the predicate function that returns the condition to check each value from the source Observable with. The function takes the item from the source Observable as the first parameter and the index, starting from 0, of the value emitted as the second parameter.

For example, we can use it as follows:

import { interval } from "rxjs";  
import { takeWhile } from "rxjs/operators";

const source = interval(1000);  
const result = source.pipe(takeWhile(x => x <= 10));  
result.subscribe(x => console.log(x));

Then we should get:

0  
1  
2  
3  
4  
5  
6  
7  
8  
9  
10

since we specified in the predicate function that x => x <= 10, which means that any value less than or equal to 10 from the source Observable will be emitted.

The skipUntil operator returns an Observable that skips items emitted by the source Observable until a second Observable emits an item.

skipWhile operator returns an Observable that skips all items emitted by the source Observable until the condition passed into the predicate function becomes false

The take operator returns an Observable that emits the first number of values emitted by the source Observable.

The takeLast operator returns an Observable that emits the last number of values emitted by the source Observable.

takeUntil operator returns an Observable that emits value from the source Observable until the Observable passed into this operator emits a value.

Finally, the takeWhile operator returns an Observable that emits the values emitted by the source Observable as long as the condition passed into this is satisfied.