Reference Types

A reference value (object) is an instance of a specific reference type. In ECMAScript, reference types are structures used to group data and functionality together and are often incorrectly called classes.

The Object Type

There are two ways to explicitly create an instance of Object.

Use the new operator with the Object constructor :

var person = new Object(); 
person.name = “Nicholas”; 
person.age = 29;

The other way is to use object literal notation.

var person = {   
 name : “Nicholas”,
 age : 29 
    };

The Array Type

Arrays are ordered lists of data, but unlike other languages, in Javascript an array can hold any type of data in each slot.

There are two was of creating an array :

Use an array constructor:

var array = new Array();
var array = new Array(20); //Passing the number of items
var array = new Array("One", "Two", "Three") // Creates an array with the 3 elements.

Or using the Array literal notation:

var colors = [“red”, “blue”, “green”]; //creates an array with three strings

Detecting Arrays

The purpose of this method is to definitively determine if a given value is an array regardless of the global execution context in which it was created.

if (Array.isArray(value)){    
//do something on the array
 }
  • Stack Methods

The push() method accepts any number of arguments and adds them to the end of the array, returning the array’s new length.

var colors = new Array();
var count = colors.push("white", "black"); //adds at the end of the array
alert(count) //2

The pop() method removes the last item, decrements the length and returns that item.

var item = colors.pop();                       //get the last item 
alert(item);   //”black” 
alert(colors.length);  //2
  • Queue Methods

unshift() adds any number of items to the front of an array and returns the new array length.

var colors = new Array();
var length = colors.unshift("white");
console.log(length) //1

shift() method which removes the first item in the array and returns it, decrementing the length of the array by one.

var colors = new Array("white", "blue");
var item = colors.shift();
alert(item) //white
  • Reordering Methods

reverse() method reverses an array.

var values = [1, 2, 3, 4, 5]; 
values.reverse();
alert(values) // 5,4,3,2,1

sort() method, sorts the array with the help of a compare function

A comparison function accepts two arguments and returns a negative number if the fi rst argument should come before the second, a zero if the arguments are equal, or a positive number if the fi rst argument should come after the second. Here’s an example of a simple comparison function:

function compare(value1, value2) { 
   if (value1 < value2) {
          return -1;    
     }  else if (value1 > value2) {
             return 1;   
      } 
      else { 
             return 0;    
      } 
   }

   var values = [0, 1, 5, 10, 15]; 
   values.sort(compare);
   alert(values);    //0,1,5,10,15
  • Manipulation Methods

concat() method, for instance, allows you to create a new array based on all of the items in the current array. This method begins by creating a copy of the array and then appending the method arguments to the end and returning the newly constructed array. When no arguments are passed in, concat() simply clones the array and returns it.

var array = [1,2];
var newArray = array.concat(3,4)
console.log(array) //[1,2]
console.log(newArray) //[1,2,3,4]

//Cloning Array
clonedArray = array.concat();
console.log(clonedArray) // [1,2]

slice(), creates an array that contains one or more items already contained in an array. The slice() method may accept one or two arguments: the starting and stopping positions of the items to return. If only one argument is present, the method returns all items between that position and the end of the array. If there are two arguments, the method returns all items between the start position and the end position, not including the item in the end position. Keep in mind that this operation does not affect the original array in any way.

//No argument => clones.
var array = [1,2,3,4,5,6];
var newArray = array.slice() //Clones the array
console.log(array) //[1,2]

//One argument -> returns the array from the position(included) until the end of the array
var array1 = array.slice(1);
console.log(array1); //[2, 3, 4, 5, 6]

//Two arguments => returns from the first argument position util the last position, not included!
var array1 = array.slice(1, 4); //Not including index 4!! 
console.log(array1); //[2, 3, 4]

splice(), main purpose is to insert items into the middle of an array, but there are three distinct ways of using this method.

The splice() method always returns an array that contains any items that were removed from the array (or an empty array if no items were removed).

Deletion — Any number of items can be deleted from the array by specifying just two arguments: the position of the first item to delete and the number of items to delete.

var array = ["a","b","c","d","e","f"];
var newArray = array.splice(1,3) 
console.log(newArray) //["b", "c", "d"] Returns the deleted items!!!
console.log(array) //["a", "e", "f"] //Removed the items from the array!!

Insertion Items can be inserted into a specific position by providing three or more arguments: the starting position, 0 (the number of items to delete), and the item to insert.

var array = ["a","b","c","d","e","f"];
array.splice(2,0,"Banana","Apple"); 
console.log(array) //["a", "b", "Banana", "Apple", "c", "d", "e", "f"]

Replacement — Items can be inserted into a specific position while simultaneously deleting items, if you specify three arguments: the starting position, the number of items to delete, and any number of items to insert.

var array = ["a","b","c","d","e","f"];
array.splice(2,2,"Banana","Apple"); 
console.log(array) //["a", "b", "Banana", "Apple", "e", "f"] //"c" and "d" have been replaced.
  • Location Methods

indexOf() method starts searching from the front of the array (item 0) and continues to the back.

var array = ["Banana", "Apple", "Orange", "Lemon", "Apple"];
var index = array.indexOf("Apple")
console.log(index); //1 - First it finds!

lastIndexOf() starts from the last item in the array and continues to the front.

var array = ["Banana", "Apple", "Orange", "Lemon","Apple"];
var index = array.lastIndexOf("Apple")
console.log(index);

The methods each return the position of the item in the array or –1 if the item isn’t in the array. You can five the methods and ad additional parameter from which to start looking.

  • Iteration Methods

ECMAScript 5 defines five iterative methods for arrays. Each of the methods accepts two arguments: a function to run on each item and an optional scope object in which to run the function (affecting the value of this). The function passed into one of these methods will receive three arguments: the array item value, the position of the item in the array, and the array object itself.

every() — Runs the given function on every item in the array and returns true if the function returns true for every item.

var array = ["Banana", "Apple", "Orange", "Lemon","Apple"];
var index = array.every(function(item, index,array) {
  if(item == "Apple")
    return true;

});
console.log(index); //False

filter() — Runs the given function on every item in the array and returns an array of all items for which the function returns true.

var array = [1, 2, 3, 4,5];
var newArray = array.filter(function(item, index,array) {
  if(item > 2)
    return true;

});
console.log(newArray); //[3, 4, 5]

forEach() — Runs the given function on every item in the array. This method has no return value.

var numbers = [1,2,3,4,5,4,3,2,1];  
numbers.forEach(function(item, index, array){    
//do something here 
});

map() — Runs the given function on every item in the array and returns the result of each function call in an array.

var array = [1, 2, 3, 4,5];
var newArray = array.map(function(item, index, array) {
  return item + 1; 
});
console.log(newArray); //[2, 3, 4, 5, 6]

some() — Runs the given function on every item in the array and returns true if the function returns true for any one item.

  • Reduction Methods

reduce() and reduceRight(). Both methods iterate over all items in the array and build up a value that is ultimately returned. The reduce() method does this starting at the first item and traveling toward the last, whereas reduceRight() starts at the last and travels toward the first.

The function passed into reduce() or reduceRight() accepts four arguments: the previous value, the current value, the item’s index, and the array object.

var values = [1,2,3,4,5];
var sum = values.reduce(function(prev, cur, index, array){    
  return prev + cur; 
}); 
console.log(sum); //15

The Math Type

The math object allows you to do mathematical calculations on numbers.

Math.round() - Returns the passed value down or up to its nearest integer.

Math​.round(​3.4​); ​// 3 
Math​.round(​3.5​); ​// 4 
Math​.round(​3.6​); ​// 4

Math.pow() - Returns the first passed value to the power of the second passed value.

Math​.pow(​10​, ​2​) ​// 100

Math.ceil() - Returns the passed value ​up​ to its nearest integer.

Math​.ceil(-​4.3​); ​// -4 
Math​.ceil(​4.01​); ​// 5

Math.floor() - Returns the passed value ​down​ to its nearest integer.

Math​.floor(​4.7​); ​// 4 
Math​.floor(​-4.3​); ​// -5

Math.min() and Math.max() - Returns the Max and Min values of a list of arguments.

Math​.min(​400​, ​2​, ​3​, ​1​, ​20​, ​30​); ​// 1
Math​.max(​400​, ​2​, ​3​, ​1​, ​20​, ​30​); ​// 400

Math.random() - Returns a random value.

Math​.random() ​// returns a random value between 0 and 1 
Math​.random() * ​100​ ​// returns a random value between 0 and 100

results matching ""

    No results matching ""