Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

'new' Operator in JavaScript. Why we use it? What does it do? and When we use it?

Hi, I am just starting out to learn basic JavaScript. I am doing a challenge on displaying current day dan time. The code looks like this:

var d = new Date();
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";

var n = weekday[d.getDay()];
document.getElementById("demo").innerHTML = n;

Though, the program works, i still do not fully understand why using 'new' operator? What does it do and when we use it. Please advise :-)

Thanks,

Will

1 Answer

In c# which i am sure is the same case with JavaScript.. the new keyword creates a new instance of the Type of class being called... so new Date() .. is creating a instance of the class Date.