Google

Jan 11, 2012

JavaScript Interview Questions and Answers: Working with the objects

Q. What are the built-in objects in JavaScript?
A. String, Date, Array, Boolean, and Math.


Q. What are the different ways to create objects in JavaScript?
A.


  • By invoking the built-in constructor.

var personObj1 = new Object(); // empty object with no properties and methods.
personObj1.name = "John"  ;     //add a property
personObj1.status = "Active";     //add a property
//add a method by associating a function to variable isActive variable.
personObj1.isActive = function() {
     return this.status;
}  



  • By creating a constructor (i.e. a template), and creating an object from the constructor. The Person constructor is like any other function, and it is a convention to start the function name with an uppercase letter to differentiate it with other functions.

function Person(name, status) {
    this.name = name;
    this.status = status;
    //add a method by associating a function to variable isActive variable.
    this.isActive = function() {
       return this.status;
    }  
   
}

var personObj1 = new Person("John", "Active");



  • Creating the object as a Hash Literal. This is what used by the JSON, which is a subset of the object literal syntax.

var personObj1 = { };    // empty object

var personObj2 = { 

   name: "John",
   status: "Active",
   isActive: function() {
       return this.status;
   }  
 
}; 


Q. Does JavaScript has a built-in concept of inheritance?
A. It does to some extent. You can think of every object as inheriting from it's "prototype".

Q. What is a "prototype" property?
A. A prototype is a built-in property of every JavaScript object. For example,

var personObj1 = new Object();  // empty object with no properties and methods.
personObj1.name = "John"  ;     //add a property
personObj1.status = "Active";   //add a property


Now, if you create another person object as shown below, all the properties will be empty, and needs to be reassigned.

var personObj2 = new Object();  // empty object with no properties and methods.
personObj2.name = "John"  ;     //add a property
personObj2.status = "Active";   //add a property

What if you want to set all the Person object status to be "Active" by default without having to explicitly assign it every time? This is where the "prototype" property comes in handy as shown below.

var personObj1 = new Object();            //empty object with no properties and methods.
personObj1.name = "John"  ;               //add a property
personObj1.prototype.status = "Active";   //add a prototype property that will set "Active" as the default


var personObj2 = new Object();  // empty object with status="Active" will be created.
personObj2.name = "John"  ;     // add a property




When you create an object via a constructor as in var personObj1 = new Person("John", "Active"), the prototype property is also set. When you actually create an object via a constructor, the new operator actually performs the following tasks.

STEP 1: Creates an empty object as in var personObj1 = new Object();

STEP 2: Attach all properties and methods of the prototype of the function to the resulting object.

STEP 3: Invoke the function "Person" by passing the new object as the "this" reference.


It is important to understand that, all the objects that are created via a constructor function will have the same prototype. This means, if you modify any one object that has been created via the constructor, you will be modifying all the objects that have been created and the new ones you will be creating via the constructor function. You can think of this as every object is inheriting from it's prototype. So, the above approach of individually adding to some properties as in

personObj1.prototype.status = "Active";  

can be very handy for methods and constants, and this "prototype" approach is used by many JavaScript frameworks.

Q. What are some of the best practices relating to coding with JavaScript?
A.

  • Use proven frameworks like jQuery, EXT JS, etc to ensure cross browser compatibility, and quality code.

  • Provide a clean separation of content, CSS, and JavaScript. This means store all Javascript code in external script files and build pages that do not rely on Javascript to be usable.


    Instead of:


    <input id="btn1" type="button" value="click-me1" onclick="test()"/>
    

    Use:

    <input id="btn1" type="button" class="something" value="click-me1" />  
    

    The above page snippet does not depend on the JavaScript function. The JQuery function below

    $('input.something').click(function(){
        //do something here
        alert('The button is clicked');
    });
    


    jQuery allows you to easily attach a click event to the result(s) of your selector. So the code will select all of the <input /> tags of class “something” and attach a click event that will call the function.

    Also instead of

    if(someCondition)
        document.write("write something ........... ");
    

    Use:

    <div title="something"> ... </div>
    


    var titleElement = $('div[title="something"]');
    titleElement.text('Better Approach');
    

    The above page is renedred as 100% (X)HTML without requiring the JavaScript to write something.



  • Use code quality tools like JSLint.

  • Use unit testing frameworks like Jasmine, qUnit, etc.


  • Use "===" instead of "==". If two operands are of the same type and value, then === produces true and !== produces false. If you use "==" or !="" you may run into issues if the operands are of different types.


  • Avoid using the eval(…) function as it poses a security risk and can also adversely affect performance as it accesses the JavaScript compiler.


  • Namespaces are essential for avoiding type name collisions. JavaScript does not have packages as in Java. But in JavaScript, this can be simulated with empty objects. For example


var MyPage1 = { };   // empty object acting as a namespace

MyPage1.Person = function(name, status) {
    this.name = name;
    this.status = status;
}

MyPage1.Person.protoyype  = 

{
    isActive: function() {
         return this.status;
    }

}


var personObj1 = new MyPage1.Person("John", "Active");
console.log(personObj1.isActive());



  • Simulate encapsulation with Douglas Crawford's approach as shown below as JavaScript does not have access modifiers like private, protected, etc as in Java.


function Person(name, status) {
      this.get_name = function( ) { return name; }
      this.get_status = function( ) {return status; }
}

Person.prototype.isActive = function( )
{
      return this.get_status();
}


var personObj1 = new Person("John","Active");
console.log(personObj1.isActive( )) ;
 
 
  • Favor the JavaScript literal way with { … } as opposed to the new Object() to create new objects as the literal way is much more robust and also makes it simpler to code and read.

  • Favor [ ] to declare an array as opposed to an array object with new Array( ). For example,
var vehicles = ['Car', 'Bus'] ; // creates an array


var vehicles = new Array( ); // creates an array object
vehicles[0] = 'Car' ;
vehicles[1] = 'Bus' ;


  • Favor using semicolons (;), and use comma separated variables as opposed to repeating vars. For example


//okay
var x = 5;
var y = 6;
var z = 9;

var x =5, y=6,z = 9; // better
 
  • Use console.log(...) as oppose to alert(...); for debugging.
    
    



More JavaScript Q&A

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home