Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Literal vs Constructor notation for primitives, which is more proper for starters? [closed]

So I am a TA for a class at my University, and I have a bit of a disagreement about how to present datatypes for absolute beginner programmers (In which most never programmed before). My teacher tells students they must strictly use constructors to create primitive datatypes such as Numbers and Strings, her reasoning is to treat JavaScript as if its strongly typed so students will be used to the languages that are in the future. I understand why, but I think it has bad trade-offs.

var num = new Number(10); // This is encouraged.

var num = 10; // This is discouraged (students will lose points for doing this).

My instructor does not make a distinction between these and students are told to treat them as if they are primitive Numbers, Strings, etc. Although I believe at least for starters who don't know better to use datatype.valueOf() when necessary, and don't know much at all what objects are yet. Literal notation would be (and I consider it to be) more proper and standard, the other way would cause confusion. Since there a consistency issues with constructor notation because they are objects (and I don't want students to worry about that). For example these don't make sense to beginners:

var num1 = new Number(1);
var num2 = new Number(1);

if(num1 === num2) ... ; // Does not run.    

if(num1 == num2) ... ; // Does not run.

if(num1 == 1) ... ; // But this does.    

var num2 = new Number(2);

if(num1 < num2) ... ; // So does this.

switch(num1){
    case 1:
        ...  // Does not run.
        break;
    default:
        ... // This runs
        break;
}

As you can see this would be confusing for someone just learning what an if statement is.I feel as if she is encouraging bad practice and discouraging good practice. So what do you think between literal and constructor notation for primitive values, which is considered more standard/proper and which is better for beginners to use?

like image 646
Spencer Wieczorek Avatar asked Jan 28 '14 02:01

Spencer Wieczorek


People also ask

Can a JavaScript constructor return a primitive value?

Code Inspection: Constructor returns primitive valueReports a constructor function that returns a primitive value. When called with new , this value will be lost and an object will be returned instead. To avoid warnings, use the @return tag to specify the return of the function.

What is the difference between constructor and prototype in JavaScript?

A constructor is a pointer. It points to the Function() that created the point from which you are retrieving the constructor from. The keyword prototype is a property of Function() objects. No other type of objects have this property.

What is constructor what are the properties of constructor?

Constructors are called automatically when the objects are created. Constructors should be declared in the public section to be availabile to all the functions. Constructors do not have return type , not even void and therefore they can not return value.

Which constructors are always called automatically?

Static constructors are called automatically, immediately before any static fields are accessed, and are generally used to initialize static class members.


2 Answers

As someone who spent extra time creating a main function in every Python program so that we'd be more prepared for Java's public static void main when the time came, there is a place for slightly-less-than-best practices when it comes to learning how to programming.

Now a teacher myself, using constructor functions in JavaScript is not that place. First, it results in misbehavior with control flow, an essential part of the beginning steps of programming. Secondly, it does the students a disservice by mis-teaching an essential language in the web developer's toolkit. Finally, it does not prepare one for constructors! As a side note, JavaScript does not easily fall into any typical programming paradigm, and as such is unsuitable as a first language in a four-year college curriculum (in this author's opinion).

Constructor functions block understanding of control flow

Firstly, let's look at control flow. Without control flow, a beginner may never be able to construct anything more complex than Hello world. It is absolutely essential for a beginner to have a solid understanding of each item in the control flow basket. A good instructor will provide several examples for each type, as well as a full explanation of what the difference is between true and truthy.

Constructor functions completely ruin a beginner's understanding of control flow, as in the following example:

var myBool = new Boolean(false);
if (myBool) { console.log('yes'); } // 'yes' is logged to the console.

Yes, this is one of JavaScript's 'wat' moments. Should the language act like this? Probably not. Does it? Absolutely. Beginners need to see simple examples that make sense to the uninitiated mind. There is no brain space for edge cases when first starting out. Examples like this only do a disservice to those the professor is supposed to be teaching.

Constructor functions have no place in JavaScript

This one's a bit more opinion-based. A caveat: JavaScripters may find some use for constructor functions in using them to convert between types (i.e. Number('10')) but there are usually better ways.

Virtually every time a constructor function is used in JavaScript, it's a misuse. I am of the mind that if one wants a literal number, just write that out. No need for all the extra typing, not to mention the various type conflicts and hidden gotchas that come from using constructors](https://stackoverflow.com/a/369450/1216976).

It's worth noting that both JSLint and JSHint (written by people much smarter than I) discourage the use of constructors in this fashion.

like image 64
SomeKittens Avatar answered Nov 11 '22 07:11

SomeKittens


new Number(1) and 1 are not the same. The first one is an Object, and the latter one is a Number.

var num = new Number(1);
typeof num;    //object

var num = 1;
typeof num;    //number

In order to get the value of the object created by the constructor, one must use valueOf every single time in order to get a correct result.

if( new Boolean(false) ){            if( new Boolean(false).valueOf() ){
    console.log("True");                 console.log("True");
}else{                               }else{
    console.log("False");                console.log("False");
}                                    }

//> True                             //> False
//Student Be Like:                   //Student Be Like:
// What?! That doesn't even make     //Okay that makes sense.
// sense!

Because of the fact that using constructors will only confuse more learners and will cause more problems in further development of your program, IMO primitive constructors should never be used. (except in certain cases.)

Furthermore, using Constructors every time you declare a variable will greatly impact your execution speed because of the fact that allocating spaces for a new object takes longer than just a simple 64-bit floating point number. Here is the comparison: http://jsperf.com/constructors-vs-literalss

tl;dr

var num = new Number(10);  // bad, never do this, prone to errors

var num = 10;              // do this instead

Every time when there's a literal and your don't use it: Very likely to be bad code.

new Boolean(false);    // bad
new String("foo");     // bad
new Object();          // not as bad as the ones above, but still bad
new Array(10);         // bad, it initializes the array with
                       //  not-your-normal `undefined`
like image 26
Derek 朕會功夫 Avatar answered Nov 11 '22 08:11

Derek 朕會功夫