[JavaScript] Built-in Libraries

JavaScript provides ready-to-use objects and functions. Also the good news is that the new versions of JavaScript (ECMAScript 5 and later) add more functionalities.

  • Array
  • Regex
  • Timer

Built-in Data Objects

JavaScript has many data types and they are objects.

  • String
  • Number
  • Date

Nobody can memorize everything. Please refer to the references to check the details.

JavaScript | MDN (mozilla.org)

JavaScript Tutorial (w3schools.com)


Array Object

JavaScript array is an object, so it has properties such as “length” and methods.

  • untyped: an element may be of any type
  • zero-based
  • dynamic: can be grown and shrunk as needed

Some basic methods are:

  • toString()
    • converts an array to a string and returns the result
  • concat(array2, array3, …, arrayX)
    • joins two or more arrays and returns a new array
  • join(separator)
    • joins all elements of an array into a string; the default separator is a comma
  • slice(start, end)
    • selects a part of an array and returns the new array
    • the element at the end index is not included in a result
    • just omit the end index if you want to slice an array to the end element.
var arr1 = ['Hello', 'World'];
var arr2 = ['Morning', 'Afternoon', 'Evening', 'Night'];

alert('Length arr1 = ' + arr1.length+', Length arr2 = ' + arr2.length);

var arr3 = arr1.concat(arr2);
alert('Length arr3 = ' + arr3.length + ' - ' + arr3.toString());

var arr4 = arr1.join('-');
alert(arr4);

var arr5 = arr2.slice(1, 3);
alert('Length arr5 = ' + arr5.length + ' - ' + arr5.toString());

A new JavaScript engine provides new methods for iteration, filtering, and searching. In the previous version, to perform these tasks, you need to iterate each item using the “for” loop and do the appropriate works. Now you can create the delegate function and pass it as an argument to one of the new methods. The code becomes much cleaner.

  • forEach()
  • map()
  • filter()
  • every() / some()
  • reduce() / reduceRight()
  • indexOf() / lastIndexOf()

Most new methods accept two arguments.

  • A call-back function 
  • A context object for “this” 

And the call-back function accepts up to 3 arguments.

  • value: the current element in an array
  • index: the index of an element in an array
  • array: array being traversed

The return value of the function is very important because each method handles the return value differently.

forEach()

The “forEach()” method iterates an array and invokes the function for each element.

function calTotal(value, index) {
  this.total += value;
}

let nums = [1, 2, 3, 4, 5];
let sum = { total: 0 };
nums.forEach(calTotal, sum);
alert(sum.total); // 15

map()

When you need to modify the content of an array, you should not touch the array while it is iterated.

The better way is the “map()” method.

  • It returns a new array.
  • The call-back function maps the element of an original array to the element in a new array.
function calSubtotal(value, index) {
  this.total += value;
  return this.total; // subtotal
}


var nums = [1, 2, 3, 4, 5];
var sum = { total: 0 };
var subTotals = nums.map(calSubtotal, sum);

alert(subTotals.toString()); //1,3,6,10,15
alert(sum.total); // 15

filter()

The “filter()” method returns an array whose elements match the condition provided as a function. The function should return true or false.

var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var oddNums = nums.filter( v => v % 2 == 1 );
var evenNums = nums.filter(function (v) { 
  return v % 2 == 0; 
});

alert(oddNums.toString()); //1,3,5,7,9
alert(evenNums.toString()); //2,4,6,8

every() / some()

These 2 methods return true or false when all or some elements of an array match the provided predicate function.

var nums = [1, 2, 4];
var isAllOdd = nums.every(v => v % 2 == 1);
var isSomeOdd = nums.some(function (v) { 
  return v % 2 == 1; 
});

alert(isAllOdd); // false
alert(isSomeOdd); // true

These methods are very useful when you verify the data.

var nums = [1, "Hello", 4];
var isAllNumbers = !(nums.some(isNaN));
alert(isAllNumbers); // false

reduce() / reduceRight()

The “reduce()” method is used to produce a single result using all elements in an array. For each step, the result is accumulated.

  • reduce(function, initialValue)
  • reduceRight(function, initialValue)

The parameters of the call-back function are also different.

  • The first parameter is the accumulated result so far.
  • The second one is the value of an iteration.
  • The third one is the index of an iteration.
function calSum(result, value) {
  return result + value;
}

var nums = [1, 2, 3, 4, 5];
alert(nums.reduce(calSum, 0)); // 15
alert(nums.reduce((r, v) => r*v, 1));  // 120

indexOf() / lastIndexOf()

Searching the value in an array becomes very easy now.

  • indexOf(value, startIndex)
  • lastIndexOf(value, startIndex)

They return the index of the first matching element.

var nums = [1, 2, 1, 2, 3, 1, 2, 1];

// searching 1
var index = nums.indexOf(1); 

// if not found, -1 is returned
while (index != -1) { 
  // 0,2,5,7
  alert(`1 is located in nums[${index}].`); 
  index = nums.indexOf(1, index+1);
}

Regex

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s