Image Image Image Image Image
Scroll to Top

To Top

JavaScript Archives - THEMWEBS

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);

07

Aug
2014

In JavaScript

By Manny

Reserved JavaScript names and keywords

On 07, Aug 2014 | In JavaScript | By Manny

When writing JavaScript there are keywords that are reserved and one is not allowed to use these words to declare variable names or object properties.

They are as follow:

15

Jun
2014

In JavaScript

By Manny

Defining functions in JavaScript

On 15, Jun 2014 | In JavaScript | By Manny

JavaScript functions come in three different flavours.

Statement

Expression

Constructor

run the code below in your console or html page.