Image Image Image Image Image
Scroll to Top

To Top

JavaScript Archives - THEMWEBS

20

Apr
2018

In JavaScript

By Manny

Reverse a string algorithm with JavaScript

On 20, Apr 2018 | In JavaScript | By Manny

Ever wondered how many different ways you can write a reverse string algorithm in JavaScript?

You can use a combination of helper methods built into JavaScript:

split(”);
The split method separates the string into substrings, which are separated by a given separator. The separator can be a blank space, comma or whatever you need.

reverse();
The reverse method changes the order of the element in the array in situ at call time. The zeroeth element will become the last element in the array and the last element the first in the array.

join(”);
The join method will recombine all the given items in the array and then return the array.

Tags |

15

Apr
2018

In JavaScript

By Manny

JavaScript map array helper method

On 15, Apr 2018 | In JavaScript | By Manny

Map is used when you want to modify data in some list or array and return a new modified array from that original array.

I’m really enjoying cryptocurrency and all the fanfare that comes with it, so let’s use an array of crypto prices in our code example.

Let’s:

  1. iterate through the array
  2. pull out all the prices which happen to be the second property of each currency object
  3. save these prices into a prices array

01

Jan
2017

In JavaScript

By Manny

What is a forEach method

On 01, Jan 2017 | In JavaScript | By Manny

The forEach method is a special kind helper method available to us on an array.  It helps us loop/iterate over an array. It is an alternative method to iterating over an array using a for loop.

for loop

var cars = [ 'Lambourgini', 'Porsche', 'Ferrari', 'Mazarati'];

for (var i = 0; i < cars.length; i++) {
  console.log(cars[i]);
}

forEach

var cars = [ 'Lambourgini', 'Porsche', 'Ferrari', 'Mazarati'];

cars.forEach(function(car){
  console.log(car);
});

When we call the forEach method we pass it an anonymous function, this is that internal argument. This function gets called one time for element in the cars array. This function can also be called the iterator function. In this example it will get called four times.

We can also extract the anonymous function to a listCars function that will later be passed in as an argument to the forEach method.

var cars = [ 'Lambourgini', 'Porsche', 'Ferrari', 'Mazarati'];

function listCars(car){
  console.log(car);
}

cars.forEach(listCars);