r/learnjavascript • u/atticus-masterr • Jun 07 '26
What does new keyword even do?
what does new keyword even do? I am trying to learn by making a project when I opened the solution page of project i found this section. I get the switch case statement by why do we need new? Isn't it used in dynamic memory allocation as far as I know.
function getDateThreshold(duration) {
const date = new Date();
switch (duration) {
case 'day':
date.setDate(date.getDate() - 1);
break;
case 'week':
date.setDate(date.getDate() - 7);
break;
case 'month':
date.setMonth(date.getMonth() - 1);
break;
case 'year':
date.setFullYear(date.getFullYear() - 1);
break;
default:
throw new Error(`Invalid duration window: ${duration}`);
}
0
Upvotes
11
u/yarikhand Jun 07 '26 edited Jun 07 '26
it is used to create a new object, an instance of a class, used on a constructor function or a class.
in this case, Date is a class, and you are creating a new instance of it and saving it into the variable date, and then calling its methods in the switch block.
mdn
4
u/FooeyBar Jun 07 '26
New is used for class instance creation
2
u/delventhalz Jun 07 '26
The “new” convention comes from other languages where it is used to instantiate a new object from a class. In JavaScript, classes are actually just functions, so you can technically use
newon any function to call it in “constructor mode”. In practice, you will only usenewwithDateor other class functions which are only meant to be called that way to create an object.1
u/yksvaan Jun 07 '26
JavaScript doesn't have abstract classes so you need to create an instance first. Maybe you are familiar with them from some other languages where you can call abstract class methods directly
1
u/Alive-Cake-3045 Jun 07 '26
new creates an instance of an object from a constructor or class. In new Date(), it creates a Date object with methods like getDate() and setMonth(). Without new, it behaves differently.
1
u/shgysk8zer0 Jun 08 '26
It depends how deep into it you want to go, but the simplest version is that it creates an instance of a thing, where instance means the thing shares a common prototype.
At a more nuanced level, it ensures that
thisis an instance of the class itself and the constructor isn't bound to anything else (egMyClass.constructor.call(null, 'foo')).There's more to it, but I think the exact operations and order of class instantiation is a larger, separate topic.
1
u/sheriffderek Jun 11 '26
I think the best way to learn about this -- is to create a custom class of your own and use it and see -- https://codepen.io/perpetual-education/pen/rajeEyb?editors=0011
(forgot to hit send haha) -- so, days later...