Home Object-Oriented JavaScript JavaScript Interview Questions: Object-Oriented JavaScript
formats

JavaScript Interview Questions: Object-Oriented JavaScript

Object Properties and Methods

In JavaScript, Objects have two things: properties and methods. Methods are simply properties that have a function assigned to them.


var foo = {
  color : "red",
  getColor : function(){
    //make this function return foo.color
    //without using the word: "foo"
  }
}

Q: Given the above code, what line of JavaScript would allow foo.getColor to return the value of foo.color, without using the word “foo”?

A: return this.color

Explanation:
When a function is a property of an object, it is called a “method”. Inside of a method, the JavaScript “this” keyword refers to the object to which the method belongs. In foo’s getColor method, if you return “this.color”, you will return the value of foo’s “color” method. The advantage to this over “return foo.color” is that when using “this” instead of “foo”, the code in the getColor method is re-usable.


Q: True of False: A function can have its own properties and methods.

A: True

Explanation:
Functions inherit from Object. You can add properties and methods to a function at any time. Run the following code in your JavaScript console and you will see this behavior:

//create a function
function foo(){};

//assign a property
foo.color = 'red';

//assign a method
foo.sayHello = function(){
    alert("hello!");
};

//inspect the object
console.dir(foo); //inspect the properties and methods of off

//execute the method
foo.sayHello();// "hello!"

//overwrite a method
foo.sayHello = function(){
    alert("this is a different message");
};

//execute the method
foo.sayHello();// "his is a different message"

Object Syntax

There are different ways to access the properties of an object: bracket notation and dot notation. Care must be taken when deciding which syntax to implement as their behavior differs.

Q: What is the difference between using dot notation and bracket notation when accessing an object’s property?

A: If using dot notation, the property must be a string and refer to a property that exists. When using bracket notation, any valid JavaScript expression that produces a value can be used inside the brackets, such as a variable or an an array element.

Hint:

These are all valid lines of code:

foo = bar.name;
foo = bar["name"];
foo = bar[5 + 5];
foo = bar[ baz() ];
foo = bar[ baz[i] ];

Q: What is important to remember about the last property’s value in a JavaScript object literal?

A : The last property’s value should not be followed by a comma.

Hint: Most browsers will let you get away with it if you forget, but Microsoft Internet Explorer will complain about the extra comma.


Q: Given the following code, what is very likely the reason that the programmer made the first letter of “Foo” a capital letter?

var Foo = function(){
this.foo = "bar";
}

A: Foo is meant to be used as a constructor function


Q: Given the following code, how would you instantiate the function “Foo” and assign it to the variable “bar”?

var Foo = function(){}

A:

var bar = new Foo();

Here is a jsFiddle.net example: http://jsfiddle.net/vs2Fg/


Creating Objects

There is more than one way to create an object in JavaScript. Which method you chose depends on the type of Object you need to create. For example, there is a difference between an Object Literal and and instance object in JavaScript. Also, while arrays are instances of the Array() constructor, they are still considered object.

Q:What are two ways in which the variable “foo” can be assigned to an empty object?

A:

  1. var foo = new Object();
  2. var foo = {};

Explanation:
When creating a new empty object, you can instantiate the Object() constructor, or you can simply create an empty object literal. In either case, you can then add properties to the new object.
Here is a jsFiddle.net example: http://jsfiddle.net/W6X2T/


Q: True or False: When you create an object literal, you must first instantiate the Object() constructor

A: False

Explanation:

In order to create an Object Literal, you assign a variable to an object. The syntax is as simple as var foo = {}. A constructor function is used when creating an instance object, which is a different process.


Q: True of False: You can only instantiate a JavaScript constructor function once.

A: False

Explanation: You can make as many instances as you want.


Q:When using the addEventListener() method to create a click-handler for a DOM element, what is the value of “this” inside of the callback you specify?.

A:The DOM element that was clicked.

Helpful Links:

The JavaScript “this” Keyword Deep Dive: jQuery Click Handlers | Kevin Chisholm – Blog

The value of this within the handler

Javascript – Advanced event registration models


Different Types of Objects

There is more than one type of object in JavaScript. Some examples are: Functions, Arrays, DOM objects and Date objects. Even NULL is technically an object, although it cannot be mutated.

Q: True or False: A JavaScript array is not an object

A: False

Explanation: JavaScript arrays are objects. They inherit from the JavaScript Object, and have methods and properties that are specific to arrays such as “length” and “sort

Here is a jsFiddle.net example: http://jsfiddle.net/D2REh/


Q: If a string is a primitive value, why does it have a split() method?

A:
Because any string has a wrapper object that provides numerous methods for that type.

Explanation:
Although primitive JavaScript values do not enjoy the “first-class” nature of objects, they have wrapper objects that temporarily “wrap” the primitive value and provide various methods. Once a primitive wrapper’s method has finished executing, that primitive value is un-wrapped and returned to its normal primitive state.

Helpful Links:

Wrapper Objects | Javascript: The Definitive Guide
Minitech: The difference between primitive types and their object wrappers


Q: What is the name of the object that refers to the application used to view a web page?

A:
The “navigator” object


Q: Which object.property combination provides a reference to the protocol used to view the current web page?

A:
location.protocol


Q: True or False: The object returned by the document.getElementsByTagName() method is an array

A:
False

Explanation:
The object returned by the document.getElementsByTagName() method is an “HTMLCollection”. This is an array-like object that has a “length” property, can be enumerated, but is not an actual JavaScript array.

Helpful Links:

document.getElementsByTagName – Web API reference | MDN

HTMLCollection – Web API reference | MDN


Scope

Although the concept of scope in JavaScript pertains specifically to the visibility of variables, it is difficult to master object-oriented JavaScript without also mastering scope. The two work hand-in-hand, laying the groundwork for a very powerful and expressive language.

Q: True or False: An object literal can be used to create private variables.

A:
False. Only functions can be used in JavaScript to create privacy

Explanation:
All of the properties of a object literal are public and can be easily mutated. The only way to create private variable in JavaScript is by using a function. You can make a property of an object literal a function (i.e. a “method”), and use private variables in that function, but the named property will always be public.


Q: If you omit the “var” keyword when creating a variable in a function, it becomes a property of what object?

A:
The window object

Explanation:
When omitting the “var” keyword, the variable you create becomes an “implied global”. But implied globals are not variables in a function. An implied global actually becomes a property of the window object. Although the window object is considered the “global” scope, it is an object, and any variable declared in the global scope (intentionally or otherwise), becomes a property of the window object.

Helpful Link:

Browser’s implied globals / Stoyan’s phpied.com


Context

In JavaScript, context pertains to the object within which a function is executed. Understanding context is a critical step towards writing advanced Object-Oriented JavaScript.

Q: What is the difference between a constructor function and a non-constructor function with respect to the word “this”

A: In a non-constructor function, “this” refers to the global context or if the function is a method, it refers to the object to which the method belongs. In the instance object that is returned by a constructor function, “this” refers to the instance object itself.

Explanation: JavaScript constructors are more useful when you understand how they behave differently from normal JavaScript functions and Object Literals.

Here is a jsFiddle.net example: http://jsfiddle.net/nyFyE/


Passing by Reference vs Passing by Value

It is critical to know whether a variable you are accessing has been passed by reference or value. Not knowing the difference can lead to spaghetti code and odd behavior that is difficult to troubleshoot.

Q:In JavaScript, are objects passed by reference or by value?

A:By reference

Explanation:
In JavaScript, all objects are passed by reference. When you make a change to a reference to an object, you change the actual object. Primitive types are passed by value.

Here is a jsFiddle.net example: http://jsfiddle.net/pmMLc/


Object Mutation

One of the things that makes JavaScript so expressive is its dynamic nature. Objects can be mutated at any time during the execution of your script. Those who come to JavaScript from conventional object-oriented languages such as C++ and Java sometimes find this behavior odd. One you become comfortable to working in this manner, you can start to tap into the deeper aspects of the language.

Q: True or False: Once you create an object, you can add, remove or change properties of that object at any time.

A: True

Explanation: JavaScript object are mutable.

Here is a jsFiddle.net example: http://jsfiddle.net/n3kR4/


Object Inheritance

JavaScript is a prototype-based language, which means that it differs from conventional object-oriented languages such as Java or C++. For example, when you create an array, it inherits from the Array constructor, which in-turn inherits from Object. You can create your own inheritance chain using the JavaScript prototype object.

Q: What is the name of the property that allows you to add properties and methods to an object, as well as every object that inherits from it?

A: The ‘prototype’ property.

Explanation:

Understanding JavaScript Prototypes. | JavaScript, JavaScript…


Q: How do you determine if a JavaScript instance object was created from a specific constructor or not?

A: Use the instanceof operator

Helpful links for the JavaScript instanceof operator:

https://developer.mozilla.org/en/JavaScript/Reference/Operators/instanceof

http://stackoverflow.com/questions/2449254/what-is-the-instanceof-operator-in-javascript

http://skilldrick.co.uk/2011/09/understanding-typeof-instanceof-and-constructor-in-javascript/

http://javascript.gakaa.com/operators-instanceof.aspx


Constructors

When instantiated, constructors return an instance of themselves. It is important to understand the nature of an instance object as it differs from an object literal in a number of ways.

Q: Can a JavaScript constructor return a primitive value (e.g. a number or a string)?

A: No.

Explanation:

A JavaScript constructor can only return an object. When no return value is specified, it returns an instance of itself. If an object is specified as the return value, then that object is the return value. If any value other than an object is specified as the return value, then it returns an instance of itself.

show
 
close