r/learnjavascript • • 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

22 comments sorted by

View all comments

Show parent comment

3

u/yarikhand Jun 07 '26 edited Jun 07 '26

you cannot call the methods of the class unless you create a new instance of it. so if you did Date.setDate, setDate would be undefined. you need to initialize it first.

when you create a new instance of a class, you are given an object in return, which includes whatever data its supposed to give you, and you manipulate THAT object that it gave you. the class itself is just a constructor that creates an object and gives it to you.

i am sorry if my explaination is confusing

8

u/Far_Broccoli_8468 Jun 07 '26

you cannot call the methods of the class unless you create a new instance of it. 

Unless the methods are static

3

u/yarikhand Jun 07 '26

thank you, completely forgot to mention this

-1

u/ssssssddh Jun 07 '26

You can't stop me

class Foo {
  getName() {
    return this.name;
  }
}

Foo.prototype.getName.call({name: 'pip'})

0

u/chikamakaleyley helpful Jun 07 '26

touché