How to clone an object in JavaScript

What is the most efficient way to clone an object in JavaScript?

Here is the wrong way that will not work properly

var obj1 = { a: 1, b: { c: {d: 2}, e: 3}},
	obj2 = {};
for(var key in obj1) {
	if(obj1.hasOwnProperty(key)) {
		obj2[key] = obj1[key];
console.dir(obj2); // seems the same object, but NOT

obj2 will look the same as an obj1, but it’s not a clone (because we just copied references), let’s prove that:

var obj1 = { a: 1, b: { c: {d: 2}, e: 3}},
	obj2 = {};
for(var key in obj1) {
	if(obj1.hasOwnProperty(key)) {
		obj2[key] = obj1[key];
obj1.b.c.d = 42; // Changed obj1
console.dir(obj2); // OOPS, changes of obj1 has been applied to obj2

So it’s not a clone.

Here is the most efficient “handmade” way to clone the object:

var obj1 = { a: 1, b: { c: {d: 2}, e: 3}},
	obj2 = {};
obj2 = JSON.parse(JSON.stringify(obj1));
obj1.b.c.d = 42; // Changed obj1
console.dir(obj2); // cool, obj2 still the same

BTW, in production code it’s recommended to use this way:

var obj1 = { a: 1, b: { c: {d: 2}, e: 3}},
	obj2 = {};
obj2 = $.extend(true, {}, obj1); // jQuery extend method
obj1.b.c.d = 42; // Changed obj1
console.dir(obj2); // cool, obj2 still the same

I think that it is the best way to clone the object (described above)
Here is the list of all possible ways to clone the object:

// jQuery deep copy:
var newObject = jQuery.extend(true, {}, oldObject); // 76% slower
var newObject = JSON.parse(JSON.stringify(oldObject)); // 12% slower
// jQuery copy (not deep)
var newObject = jQuery.extend({}, oldObject); // 24% slower
// simple clone function
var newObject = clone(oldObject); // fastest way, first function, that will copy only references (seems to be completely wrong way)
// ES5 Object.clone
var newObject = Object.clone(oldObject); // 85% slower

Here is the link on benchmark

So, the best production way to clone the object is still jQuery deep copy (not due to the benchmarks, but it’s the most safe and recommended way)
Let’s dig into this, and take a look under the hood. Here it the source code of jQuery extend:

Here is the “core” part

	for ( ; i < length; i++ ) {
		// Only deal with non-null/undefined values
		if ( (options = arguments[ i ]) != null ) {
			// Extend the base object
			for ( name in options ) {
				src = target[ name ];
				copy = options[ name ];
				// Prevent never-ending loop
				if ( target === copy ) {
				// Recurse if we're merging plain objects or arrays
				if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
					if ( copyIsArray ) {
						copyIsArray = false;
						clone = src && jQuery.isArray(src) ? src : [];
					} else {
						clone = src && jQuery.isPlainObject(src) ? src : {};
					// Never move original objects, clone them
					target[ name ] = jQuery.extend( deep, clone, copy );
				// Don't bring in undefined values
				} else if ( copy !== undefined ) {
					target[ name ] = copy;

So, let’s take a look at fully “handmade” function “clone”
Here is simplified similar function (but not the same)

function extend (target, other) {
  target = target || {};
  for (var prop in other) {
    if (typeof source[prop] === 'object') {
      target[prop] = extend(target[prop], source[prop]);
    } else {
      target[prop] = source[prop];
  return target;

somewhere I saw this way to clone the object


Please, do not even think about using of this. Eval is completely evil (Douglas Crockford will help you to find out the reason)

Social Share Toolbar

How to use mongoose with MongoDB in Node.js

Here is the example how to start simple project with usage of Mongoose for MongoDB on Node.js and mongoDB hosted on mongolab.

First of all you need to correct package.json file in your project to something like this

    "name": "rent",
    "version": "0.0.1",
    "private": true,
    "scripts": {
        "start": "node app"
    "dependencies": {
        "express": "3.0.2",
        "jade": "*",
        "log4js": "0.5.6",
        "mongoose" : "3.5.4",
        "moment" : "1.7.2",
        "mongoose-pureautoinc": "*"

Make sure that you have added mongoose package, other stuff just for example
Mikitas-MacBook-Air-2:test nik$ sudo npm install
or just “npm install” (for windows or if you configured permissions)
You can also use “npm install mongoose” to install it.

Let’s create mongoDB “model”. So somewhere in your DAL try this code:

var mongoose = require('mongoose')
    , Schema = mongoose.Schema
    , ObjectId = Schema.ObjectId;
// let's create scheme for some random stuff:
var postSchema = new Schema({
    _id: ObjectId,
    thumbnail: String,
    whenCreated: Date,
    whenUpdated: Date,
    comments: [{
            author: {
                authorId: ObjectId, 
                name: String, 
                thumbnail: String
            date: String, 
            text: String
    rating: Number,
    isApproved: Boolean,
    text: String
}, { collection: 'post'});
// and let's register this scheme as a model and make global for this module
module.exports = mongoose.model('Post', postSchema);

Now we can include this file:

var Post = require('../DAL/models/Post');

And use it for example to get all items from collections

exports.getPosts = function (callback){
	return Post.find({/* query */}, function (err, docs){
		if (!err) { 
		else { 
			throw err;

Note: that the operation is async and you will get result only in callback
please check this mongo docs out

Or we can insert new item into collection:

exports.addPost = function (){
    var post = new Post();
    post.rating = 5.89;
    post.text = "Here is one more post to my blog on"; 
    post.isApproved = true;
    // other fields;

Here is one more link on mongo docs

Finally, to use this “DAL” methods we need to create connection to DB.
You can use service to host your DB for free (until your DB is less then 500 mb).
After you created new BD on mongolab you can create connection with the following way:

var mongoose = require('mongoose');
mongoose.connect('mongodb://<your login>:<your password>@<your id><database name>');
// here you can call methods described above

That’s it, just several lines of code, some clicks and you have MondoDB database already hosted in web.
Perfect solution for Hackathons, fast tests and startups.

By the way, you can host you Node.js code on service also for free (until it exceeds some limitation, for details check heroku website out)

Social Share Toolbar

JavaScript Quiz

Some awkward questions that may be asked on the interview or during the JavaScript lectures.

Type conversion

var a = 1 + '2' + 3;


“123” because 1 will be converted to string and “1” + “2” is strings concatenation operation

var b = +(1 + 2 + '3' + 4) + 5;


“339” similar situation, firstly 1 and 2 will be summarized as numbers, and the result will be 3. Then conversion to string and will be concatenated “34”. After that the string “334” will be converted to the number, because of plus operator. Afterwards to the number 334 will be added 5, so the result is 339

var c = '4' - 3;


1, because the second operand is integer, so the first one will be converted to number 4


if (!("a" in window)) {
    var a = 1;


undefined. Because:

1) all global variables are properties of window. Writing var a = 1 is functionally equivalent to writing window.a = 1

2) all variable declarations are hoisted to the top of the containing scope.

variables vs functions hoisting

var a = 1,
b = function a(x) {
    x && a(--x);


1) variable declaration hoisting (where declaration is “var a;” and initialization is “a = 1;”)
2) All function declarations are hoisted to the top of the containing scope along with variable declarations. Function expressions are not hoisted.
where declaration is “function functionName(arg1, arg2) { /* function declaration – will be hoisted */ }”
and expression is “var functionName = function (arg1, arg2) {/* function expression */};”
Problem? Just read ECMA 5 (13.0)
3) function declarations override variable declarations but not variable initializations. The variable initialization overrides the function declaration.
function value() {
return 1;
var value;
alert(typeof value); //”function”


function value() {
return 1;
var value = 1;
alert(typeof value); //”number”

one more variables vs functions

function a(x) {
    return x * 2;
var a;


the answer is the body of function a:
function a(x) {
return x * 2;
Ha-ha, function declarations override variable declarations unless there’s an initialization.
So, for this case
function a(x) {
return x * 2;
var a = 1;

we gonna get – 1
Pretty cool, yep?)


function b(x, y, a) {
    arguments[2] = 10;
b(1, 2, 3);


Because each entry in the arguments object is a duplicate of each named argument.


function a() {


[object Window]
Reasons are:
1) When a method is called on an object, this points to the object on which the method resides.
2) If thisArg is null or undefined, the called function is passed the global object as the this value. Otherwise, the called function is passed ToObject(thisArg) as the this value. (in this case it will be window)
So, the code above could be converted to:
function a() {

Or, even to



typeof typeof (null)


Firstly typeof operator always returns a string value (in this case, it returns “object” for typeof(null)). null is type object and undefined is type undefined.
Whenever you have typeof typeof, the result is always “string”.




1) Numbers end up wrapped by the Number type when you use them, and the Number type has a toString()
2) The length property of a function indicates how many names arguments are expected. The toString()methods accepts one argument, which is the radix in which to output the string representation of the number (for example toString(2) outputs the binary representation of the number as a string and toString(16) outputs the hexadecimal representation of the number as a string).


var a = (1, 5 - 1) * 2;


The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand (not the second, the last one)
Some extra examples:
a = ‘hello’, ‘world’; //’world’
a = 1, 2 + 3, 4 – 1; //3

One more comma

var x = 10;
var foo = {
    x: 20,
    bar: function () {
        var x = 30;
        return this.x;
console.log(, // 1 case
  (, // 2 case
  ( =, // 3 case
  (, // 4 case


1 case – 20
2 case – 20
3 case – 10
4 case – 10
Brain damage… ?
That’s pretty simple in case if you bear in mind that in this part of the code represents a pointer to the function, and the comma operator takes on the value of that function before being called. 
Also, for case 3 function location gonna be changed to window.


function f(x, y) {
    x = 10;


undefined undefined
The arguments object and the named argument do not share memory space. When a change is made to arguments, that value is copied to the named argument. It doesn’t work the other way.
A named argument is no more special than a local variable, and so changing its value doesn’t affect the arguments object.

P.S. If you were able to solve all these quizzes, my congratulation you are cool enough! Just mail me to gmail(doggy) and I will recommend you if needed =)

Social Share Toolbar

JavaScript design patterns

Here are the most common JavaScript solutions that should be used in production code, everybody calls this list as JavaScript Design Patterns, but I think that it’s just good code’s rules. By the way, here they are:

immediate function pattern
purpose: to wrap some code in the context. Let us reduce polluting of the global context

(function () {
} ());

purpose: the same solution, but with saving of results

var someVar = (function () {
    return 'result';
} ());

purpose: here is the real world example, it allows to use $ symbol as a jQuery in one context and as a Prototype library in another context without polluting of the global context. This solution must be used with any external library.

(function ($) {
} (jQuery || $));

note: Immediate function wrapped in parens, because:

  • Without parens it would be interpreted as function declaration (not expression) which is syntax error
  • Function expression can not start with word “function”

What is a Function Declaration?

function foo() {
    return 'result';

What is a Function Expression?

var bar = function () {
    return 'result';

immediate object initialization pattern
purpose: This pattern is mainly suitable for one-off tasks, and there’s no access to the object after the init() has completed. If you want to keep a reference to the object after it is done, you can easily achieve this by adding return this; at the end of init().

    width: 100,
    height: 200,
    getArea: function () {
        return this.width * this.height;
    init: function () {
        //other init code

memoization pattern
purpose: the main goal is performance optimization. It’s real deal to save pre-calculated results. E.g. for Fibonacci numbers, juat implement solution with and without this pattern and you will see the difference.

function average(x, y) {
    var key = x + '_' + y;
    if (!average.cache.hasOwnProperty(key)) {
        average.cache[key] = (x + y) / 2;
    return average.cache[key];
average.cache = {};
average(10, 20); //calculate
average(10, 20); //take from cache
average(20, 10); //calculate

Loop closure pattern
purpose: to eliminate “cycle f**k ups”, I mean the situation when you use cycle iterator variable in closure and you expect 1, 2, 3 .. values in different functions, but you have always last value in all.

var arr = ['one', 'two', 'three'];
for (var i = 0, len = arr.length; i < len; i++) {
    (function (i, d) {
        //access index and data
        console.log(i + ') ' + d);
    } (i, arr[i]));

The same code with jQuery

var arr = ['one', 'two', 'three'];
$.each(arr, function (i, d) {
    console.log(i + ') ' + d);

implementation is similar to

var forEach = function (d, f) {
    for (var i = 0, l = d.length; i < l; i++) {
        f(i, d[i]);

Private member
purpose: restrict access to private members

function Semaphore(start) {
    var value = start; //private variable
    //private method
    function resetValue(){
        value = 0;
    return {
        enter: function () {
        leave: function () {
        getValue: function(){
            return value;
var sem = new Semaphore(0);
Assert(!sem.hasOwnProperty('resetValue'));//could not access private method
Assert(!sem.hasOwnProperty('value')); //could not access private variable

Optional parameter pattern

purpose: add ability to specify optional parameters
When function has a lot of parameters

function Car(name, model, color, number, wheelsRadius, year, autoTransmission) {
    //do something with all parameters
    return 'result';

This is bad code, because all parameters must be set when instantiating (even optional parameters)

var myCar = new Car('Honda', 'civic', 'red', null, null, 2004, false);

also the order of the parameters is fixed and it’s hella hard to add one more parameter, when this is boilerplate code

So, the decision is to convert list of parameters to one object…

function Car(settings) {
    var defaultSettings = {
        name: 'Unknown',
        model: null,
        autoTransmission: false,
        wheelsRadius: 16
    this.settings = $.extend({}, defaultSettings, settings);
    return this.settings;
var myCar = new Car({ name: 'Honda', model: 'civic', color: 'red', year: '2004', autoTransmission: true });

Note: if function has more then 3 parameters it must be converted to the function with one object-parameter.

Namespace pattern
purpose: reduce pollution of global context and simplify code organisation.
Here is Bad practice (pollute global scope):

function Init() { };
function Run() { };
var state = 1;
var module1 = {}; = [1, 2, 3];
var module2 = {};

Here is Better practice, but not good enough:

var MYAPP = {};//only one global object;
MYAPP.Init = function () { };
MYAPP.Run = function () { };
MYAPP.state = 1;
MYAPP.module1 = {}; = [1, 2, 3];
MYAPP.module2 = {};

Why not good enough? Because if you have a lot of modules, you will do something like:

if (typeof MYAPP === "undefined") {var MYAPP = {};}
if (typeof MYAPP.modules === "undefined") {var MYAPP.modules = {};}

Here is the Namespace pattern (read it carefully, it’s pretty interesting):

var MYAPP = MYAPP || {};
MYAPP.namespace = function (nameSpace) {
    var parts = nameSpace.split("."),
        parent = MYAPP,
    if (parts[0] === "MYAPP") { // strip redundant leading global
        parts = parts.slice(1);
    for (i = 0; i < parts.length; i++) {
        // create a property if it doesn't exist
        if (typeof parent[parts[i]] === "undefined") {
            parent[parts[i]] = {};
        parent = parent[parts[i]];
    return parent;

To create new (or get already existing) namespace you need to write:

var moduleCar = MYAPP.namespace("MYAPP.modules.moduleCar");

Module pattern
purpose: Javascript doesn’t have special syntax for packages, but with help of “namespace” and “immediate function” patterns we can achieve this:

MYAPP.utilities.stack = (function () {
    var stack = [];
    function push(value) {
    function pop() {
        return stack.pop();
    function somePrivateMethod() {
        stack = [];
    return { // public API
        push: push,
        pop: pop
} ());

Chaining pattern
purpose: add ability to use similar cool stuff as it possible with jQuery (I mean this chaining – $(‘.container’).html(markup).show() …)

var calculator = (function () {
    var value;
    return {
        init: function (startValue) {
            value = startValue;
            return this;
        add: function (val) {
            value += val;
            return this;
        mul: function (val) {
            value *= val;
            return this;
        result: function () {
            return value;
} ());

P.S. It’s pretty obvious, but you can use different combination of these patterns to achieve your goal.

Social Share Toolbar

slides from frontendConf

My slides from –

video with presentation:
part 1 – (Russian)
part 2 – (Russian)

Social Share Toolbar

Link folder into Visual Studio Project

As far as we all might know, Visual Studio allows to add existing file as a link.

file as a link

But sometimes it could be pretty useful to add whole folder as a link. As a result I want to change\add\remove files in one directory and to observe the same changes in the other project. The first thing that came up to my mind was hard link (yeah it’s strange).
But I was sure enough that I can make it by adding several lines to .csproj file. Here they are:

<Compile Include="..\..\..\OtherProject\CommonFolder\*.cs">

and here is the example ho to add files as a content (one file)

    <Content Include="..\WebClient\index.html">

and the whole directory

    <Content Include="..\WebClient\Pages\*.html">

Just to clarify – all these changes I’ve added to e.g. MyProject.csproj file.

Social Share Toolbar

HOW TO run Window Phone 8 emulator on parallels on mac

That awkward moment, when you want to use you windows on parallels for Windows Phone 8 development (and don’t want to install windows via bootcamp).

Shortly some helpful point:

  • first of all ensure that you have Parallels desktop 8 for mac (it’s really important to have 8 version, if not – just update it by the install 8 version)
  • go to parallels settings – “Optimisation” and check “Nested virtualisation enabled”
  • go to parallels hardware settings and ensure that you have configured ONE cpu and at least 4GB of ram (may be it will work with 2 GB I don’t know). It is really important to set only 1 CPU
  • make sure that you have installed parallels tools on your windows 8 (yep windows 8 on your parallels)
  • ensure that you have windows 8 pro edition (I had windows 8 N, then updated to windows 8 Pro N), if not – update it. Open My Computer, right click – Properties. Check your windows version, if it’s not pro, click “get more features” or something like this. You should enter serial key and wait until windows will install all cool features. (Serial keys could be taken from your msdn premium subscribtion account, if you have one, just click “get key” near the windows 8 pro, on pro N edition, copy-paste it to the windows updating window and follow the white rabbit)
  • Now you have windows 8 pro edition, cool! Find on start screen “Hyper-v manager”, configure your device emulator, and set ONE cpu, only ONE, seriously 1.
  • Now you could try to run you project in VS 2012 on device. In case if you will have an error with CPU counts, something like “…this can happen when the virtual processor or socket count…” open parallels settings and ensure that you configured one cpu, and open hyper-v manager and look at settings for device emulator you trying to run – open it’s settings and set cpu count to one
  • That was the small manual how to run windows 8 emulator on parallels for mac, or how to start hyper-v on parallels for mac.

    Social Share Toolbar

    My thoughts about future of pointing devices

    It’s cool to be on the cutting edge of new technologies, and it is cool to invent or even just try something new.
    All we have been inspired by sci-fi films with “future-rised” interfaces.
    And all we have been inspired by google glasses, it’s hella cool device

    But STOP, what’s going on with PC/Laptop’s pointing devices?
    You know, I mean “leap motion”, “mycestro” and other similar devices that reinvented kinect for PC/Laptop.
    For example here is one more DIY motion device – It is great presentation, it is interesting device, but thats it. I don’t believe that lazy people will waving their hand the whole day. It’s too hard, believe me. May be in the near future laptops and other devices will have second web-camera and somebody gonna use “leap motion\kinect like” gestures to list presentation’s slides. But I’m sure that nobody will use it in daily work, just because it’s too hard.
    I believe that mouse/trackpad device will be replaced by eye-tracking mechanism, or by the mind-PC interface, but not with the kinect like toys. It is really funny, but I think that this is totally useless

    Social Share Toolbar

    Some thoughts about html5 by Christian Heilmann – it is really cool presentation for anyone who cares about the web (by Christian Heilmann

    P.S. just put here some interesting tools:

    Social Share Toolbar

    You can’t create a button

    Here is very interesting article by Nicholas C. Zakas. Most excited point is about replacing default browser’s elements (such as checkbox, button, etc) with simple div and span elements. This patters is actively used by google, and as it was described in article it’s a mistake. Details are in the article

    Social Share Toolbar