Why is "var" not used for customized constructors?


#1



I noticed we do not use "var" for declaring customized constructors and I do not understand why they don't get explicitly declared in the same way that "Object( )" does.


https://www.codecademy.com/en/courses/spencer-sandbox/3/2?curriculum_id=506324b3a7dffd00020bf661#


function objectName(args*) { };

Vs

var objectName = function(args) { };


#2

Hello @microblaster86319,
I think you confused the jQuery's function .val(); with JavaScript's var, didn't you?

So yes, it depends, how you create an object. But I guess you just misunderstood there something.

Hope this will help you understanding :slight_smile:


#3

Sorry I meant "var" not "val"! Also, I haven't learned jQuery so that isn't it lol


#4

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var

Explains what happens with/out it


#5

That was a very helpful article but I guess you have changed the nature of my question. Specifically, why are customized constructors made without declaring them explicitly (so according to the article they are implicitly global) whereas the object or literal constructors are always explicitly declared (using the "var" keyword). What is it about the Object( ) constructor that requires it be explicitly declared using "var" and "new" every time? Is this just a random note about Javascript and there is no reason to it?


#6

Whoops, my bad.

Well, there's an article for that too:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function
The difference being that function declarations are hoisted, they are created before that scope starts executing.
They also get a name property.

new is how js knows to treat a function like a constructor, again, an article for that:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new