How to set up JavaScript namespace and classes properly?

Do neither of those things. Make a javascript “class”: var MyClass = function () { var privateVar; //private var privateFn = function(){}; //private this.someProperty = 5; //public this.anotherProperty = false; //public this.someFunction = function () { //public //do something }; }; MyNamespace.MyClass = new MyClass(); One with static vars: var MyClass = (function(){ var static_var; … Read more

Returning only certain properties from an array of objects in Javascript [duplicate]

This is easily done with the Array.prototype.map() function: var keyArray = objArray.map(function(item) { return item[“key”]; }); If you are going to do this often, you could write a function that abstracts away the map: function pluck(array, key) { return array.map(function(item) { return item[key]; }); } In fact, the Underscore library has a built-in function called … Read more

Using reserved words as property names, revisited

In ECMAScript, starting from ES5, reserved words may be used as object property names “in the buff”. This means that they don’t need to be “clothed” in quotes when defining object literals, and they can be dereferenced (for accessing, assigning, and deleting) on objects without having to use square bracket indexing notation. That said, reserved … Read more

Comparing two arrays of objects, and exclude the elements who match values into new array in JS

well, this using lodash or vanilla javascript it depends on the situation. but for just return the array that contains the differences can be achieved by the following, offcourse it was taken from @1983 var result = result1.filter(function (o1) { return !result2.some(function (o2) { return o1.id === o2.id; // return the ones with equal id … Read more

Pass object to javascript function

The “braces” are making an object literal, i.e. they create an object. It is one argument. Example: function someFunc(arg) { alert(arg.foo); alert(arg.bar); } someFunc({foo: “This”, bar: “works!”}); the object can be created beforehand as well: var someObject = { foo: “This”, bar: “works!” }; someFunc(someObject); I recommend to read the MDN JavaScript Guide – Working … Read more

What’s the difference between “{}” and “[]” while declaring a JavaScript array?

Nobody seems to be explaining the difference between an array and an object. [] is declaring an array. {} is declaring an object. An array has all the features of an object with additional features (you can think of an array like a sub-class of an object) where additional methods and capabilities are added in … Read more