2

I have a custom object that I would like to create an array of. When creating my array it creates an occurrence with empty properties, I understand why, but I would like to avoid this. I realize I could just delete the occurrence with the empty properties, but is there a better way?

function FileToPassBack(path, originalFileName, modifiedDate, newFilename) {
    if (!(this instanceof FileToPassBack)) {
        return new FileToPassBack(namepath, originalFileName, modifiedDate, newFilename);
    }
    this.Path = path;
    this.OriginalFileName = originalFileName;
    this.ModifiedDate = modifiedDate;
    this.NewFileName = newFilename;
}

function PostSelectedItems() {
    var allFilesToPassBack = new Array(new FileToPassBack());

     $('#fileNamesTable').find('tbody>tr:visible')
                         .each(function (index, element) {
                                var row = $(this);
                                if (row.find('input[type="checkbox"]').is(':checked'))
                                {
                                    var path = row.find('.pathTDClass').html();
                                    var originalFileName = row.find('.originalFileNameTDClass').html();
                                    var modifiedDate = row.find('.modifiedDateTDClass').html();
                                    var newFileName = row.find('input[class="newFileNameTDClass"]').val();

                                    var currentFileToAdd = new FileToPassBack(path, originalFileName, modifiedDate, newFileName)
                                    allFilesToPassBack.push(currentFileToAdd);
                                }
                            });

    //post path, original file name, modified date, new file name
    var objectAsJSON = JSON.stringify(allFilesToPassBack);
}

I am new to JS, so excuse me if I am way off track.

Brandon Hunt
  • 67
  • 2
  • 10

2 Answers2

1

new Array(number)

Creating a new array with a number will initialize it with a certain number of empty elements:

var a = new Array(5);
// a = ['','','','',''];

thus when you push it will add a new entry

a.push("a");
// a = ['','','','','', 'a'];

The best practice is not to use new Array, instead use [] syntax as it is more performant.

var allFilesToPassBack = [];

JSON Stringify

although it works, you need to be aware that you are stringify-ing an array not a JSON in your example code.

Update

why [] is more performant than new Array() and considered a best practice.

When you create an array using

var a = [];

You're telling the interpreter to create a new runtime array. No extra processing necessary at all. Done.

If you use:

var a = new Array();

You're telling the interpreter, I want to call the constructor "Array" and generate an object. It then looks up through your execution context to find the constructor to call, and calls it, creating your array.

why its a best practice?

The new Array() doesn't add anything new compared to the literal syntax, it only wraps the array with an object wrapper that is not needed, only adding overhead of calling the Array constructor and creating an object wrapper around the array.

additionally defining a function Array() {} in the code, new Array() will start creating new instances from this function instead of creating an array, its an edge case, but if you need an array, just declare it with [].

You never need to use new Object() in JavaScript. Use the object literal {} instead. Similarly, don’t use new Array(), use the array literal [] instead. Arrays in JavaScript work nothing like the arrays in Java, and use of the Java-like syntax will confuse you.

Do not use new Number, new String, or new Boolean. These forms produce unnecessary object wrappers. Just use simple literals instead.

http://yuiblog.com/blog/2006/11/13/javascript-we-hardly-new-ya/

There are ton of sources, but i'll keep it minimal for this update. new was introduced to the language as it is "familiar" to other languages, as a prototypal language, the new syntax is useless and wrong, instead the language should have Object.create. but thats a different topic, you can read more about it from experts like Kyle Simpson or Douglas Crockford.

Bamieh
  • 10,358
  • 4
  • 31
  • 52
  • If your claim about "best practice" and performance is true, could you back it up with a trustful source? – trincot Aug 19 '16 at 11:25
  • @trincot of course, i can explain why its more performant, and i can look for sources. i'll update my answer accordingly. – Bamieh Aug 19 '16 at 11:27
  • OK, I am curious, because on my FireFox it makes no performance difference whether I do `new Array()` or `[ ]`. There are fluctuations of one being 2% faster than the other, but it varies in both ways. – trincot Aug 19 '16 at 11:37
  • @trincot i updated my answer, the engine does crazy optimizations to the code we write, hence you don't actually know how its really interpreted by the browser engine. the only way is that you can measure is to see whats the difference between the two (as specified by the spec), which requires more steps to create? – Bamieh Aug 19 '16 at 11:40
  • The spec does not require anything about the number of implementation steps. I don't think a reference to a 2006 blog is authoritative on this matter, and I find their reason *"use of the Java-like syntax will confuse you"* a bit of an unprofessional remark. `new` is not confusing in my opinion. True, I like the short notation. But to claim it is more performant or "best practice" needs some good backing up and sound reasons, and I don't see it. – trincot Aug 19 '16 at 11:45
  • @trincot you have to understand prototypal inheritance to see whats wrong with `new` in javascript. ints not confusing in its literal sense, but in its usage in javascript. the spec **DOES** talk about the Array object which we call with `new` here is a link to the spec pdf http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%201st%20edition,%20June%201997.pdf – Bamieh Aug 19 '16 at 11:52
  • @trincot "The JavaScript Array object is a global object that is used in the construction of arrays; which are high-level, list-like objects." the notation of creating new arrays from constructors is costly, calling `[]` avoids this all along. – Bamieh Aug 19 '16 at 11:53
  • @AhmedBahieh, `[ ]` is just another syntax for the same. Both create an object that has the Array prototype. Like I wrote before, I see no performance difference. They are both as *costly*. Do you have different statistics that make you say it is *costly* with comparison to `[ ]`? – trincot Aug 19 '16 at 11:56
  • 1
    @trincot dude `[]` creates an array. `new Array()` creates an array wrapped in an object wrapper, constructed from the Array function. `[]` doesnt construct anything. it only creates an array in memory at runtime. I believe i explained clearly by now, now you believe whatever you want. – Bamieh Aug 19 '16 at 12:15
  • You explained clearly, but have it wrong. Both create (*construct*) an array. They are different syntax for *exactly* the same. The one is not more *wrapped* than the other. They produce an object with exactly the same prototype and the same owned properties. This is not belief, it is fact. – trincot Aug 19 '16 at 12:21
  • @trincot ... Ahmad Bamieh is correct. `[]` is preferred over `new Array()` He has explained it very well. See here as well, this will give another example why `[]` is preferred. http://stackoverflow.com/a/1273936/1729859 – mituw16 Aug 19 '16 at 12:23
  • OK, I read that, but apart from the fact that you can create a custom `Array` constructor which would influence the effect of `new Array` I don't see anything there that proves the performance is better. Have you read that my tests show the performance is equal? They create the same. But you are right about the exception when you create a custom constructor. I think that in itself would be far from best practice of course. Let me ask you, what is the difference in the result object created? What is the difference in performance? I see none. – trincot Aug 19 '16 at 12:27
  • @trincot Performance gains would be so small (microseconds) one way or the other (almost unmeasurable). The difference is that `[]` just creates a immediate instance of an empty array in memory. It doesn't have to go look up what the constructor of an array is, it just creates it. `new Array()` will produce the same end result, but it will have the javascript parser spend a few extra microseconds to go lookup the constructor of array. Again the performance gains are almost nothing, but best practices in JS are to create literals. You can find many many docs on this. – mituw16 Aug 19 '16 at 12:31
  • @trincot Here is another example where literal notion is preferred. http://stackoverflow.com/a/4597935/1729859 – mituw16 Aug 19 '16 at 12:32
  • 1
    @trincot we are talking about arrays not objects, objects have differences between the two as you can change the settings of the object via its constructor call. arrays have no difference only you can pass a number of params. you dont accept a resource from YUI javascript experts but give me a stackoverflow answer?! – Bamieh Aug 19 '16 at 12:37
  • Arrays are objects. True, the constructor gives a way to provide the number of arguments, but you can also use it to pass the arguments themselves. But that is irrelevant. Whether you create them with one syntax or another, the result is the same. Did I give a StackOverflow answer on this? What are you referring to? – trincot Aug 19 '16 at 12:49
0

I think, though am unsure what your actual problem is, that you are calling var allFilesToPassBack = new Array(new FileToPassBack()); to initialize your array? You don't need to do that.

Try replacing that line with this instead.

var allFilesToPassBack = []

That will init an empty array than you can then pushto in your jquery each loop.

mituw16
  • 5,126
  • 3
  • 23
  • 48
  • This worked. Thanks. My formal training is C#, so I want everything to be strongly typed. – Brandon Hunt Aug 19 '16 at 11:27
  • Mine is too, takes a while to remember JS is not strongly typed :) – mituw16 Aug 19 '16 at 11:27
  • @BrandonHunt not that i mind or anything, but im wondering why is this the accepted answer? its answered after my answer, and my answer explains the reason why you should use `[]` with code example aswell .. – Bamieh Aug 19 '16 at 11:43
  • @AhmadBamieh I answered before you did. That is probably why. – mituw16 Aug 19 '16 at 12:08
  • It says mine was answered 6 minutes before yours, its okay – Bamieh Aug 19 '16 at 12:17
  • 1
    @AhmadBamieh Can you read and do math? It says on mine, "answered 58 minutes ago" It says on yours "answered 52 minutes ago" ... Simple logic would tell you that my answer has been around **longer** which would mean that I answered first. I don't really care if you answer is accepted or mine is (just want to help OP), but don't try to say you answered first. – mituw16 Aug 19 '16 at 12:19