Pages

Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Monday, September 12, 2016

Object Creation in Javascript

In Javascript, we don't have classes. Instead we use functions. There are two ways to create custom objects.

1. Constructor function
2. Literal Notation

1. Creating an object using constructor function;
        In this method, we first create a function and then create an object using that function.

function Employee(firstName, lastName){
      this.firstName = firstName;
      this.lastName = lastName;

      this.getFullName = function(){
            return this.firstName + " " + this.lastName;
      }
}

var employee = new Employee("Hello","World");

Here, employee is the object and Employee is the constructor function.


2. Literal Notation:

 var employee = {
        firstName : "Hello",
        lastName : "World",
        getFullName : function () {
                      return this.firstName + " " + this.lastName;
        }
}

        document.write("FirstName = " + employee.firstName + "[br/]");
        document.write("LastName = " + employee.lastName + "[br/]");
        document.write("FullName = " + employee.getFullName() ;

In this method, we already have the object. Here, employee is the object name. So, we can access the properties using that object name. Objects created using this method are singletons i.e. any changes to one instance affects the entire script.

Friday, September 9, 2016

Remove duplicate values from array using Javascript

Filter method in JavaScript can be used to easily remove duplicate values from an array in JavaScript.

Syntax:
array1.filter(callbackfn[, thisArg])

Filter method takes two parameters described as below:
Parameter
Definition
array1
Required. An array object.
callbackfn
Required. A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.
thisArg
Optional. An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

Return Value

A new array that contains all the values for which the callback function returns true. If the callback function returns false for all elements of array1, the length of the new array is 0.
This property of filter method can be used to remove duplicates from an array.
Code:
var myArray = ["a","b","c","a"];
var newArray = myArray.filter(function(vale,index,array){
  return array.indexOf(value)==index;
});
alert(newArray);

indexOf(value) returns the first index of value. If it is not equal to the current value, filter returns false, so the value is not included in newArray. Thus, newArray will have unique values only.