Dev Video: Javascript for-loops are complicated – HTTP203


JavaScript for-loops areā€¦ complicated – HTTP203


> Looping sure is complicated in JavaScript. There are 4 different types of loops that have the word `for` in them.
The gist below show you a basic for, for-in, for-of, and for-each loop in Javascript.

Confused yet?
Well in Google Go, they solved this problem by only having 1 type of loop. And it’s a for loop.

Larry Battle

I love to program, and discover new tech. Check out my stackoverflow and github accounts.

More Posts - Website

Follow Me:
TwitterLinkedInYouTube

Code of the Day: Javascript Date.prototype.setDay()

In Javascript, I find it strange how `Date.prototype.getDay()` in defined but `Date.prototype.setDay()`.
So here’s the code for `Date.prototype.setDay()`.

// Sets the Date object to the day of the week.
// @param {Number} - dayIndex must be from 0 - 6, where 0 is sunday.
// @return {Number} returns the primitive value of the Date object.
Date.prototype.setDay = Date.prototype.setDay || function (dayIndex) {
	dayIndex = Math.floor(+dayIndex);
	if (dayIndex < 0 || 6 < dayIndex) {
		throw new Error("Must pass integer between 0-6, where sunday is 0.");
	}
	this.setDate( this.getDate() + dayIndex - this.getDay() );
	return this.valueOf();
};

Demo 1

var a = new Date(Date.parse("Feb 1, 2014"));
a.setDay(0);
console.log(a.toDateString() === "Sun Jan 26 2014" );
a.setDay(6);
console.log(a.toDateString() === "Sat Feb 01 2014" );

Demo 2

// Prings the Monday - Friday for the current day.
var getWeekString = function () {
	var days = [],
		date = new Date();
 
	for (var i = 1, len = 6; i < len; i++) {
		date.setDay(i)
		days.push("## " + date.toDateString() );
	}
	return days;
};
console.log(getWeekString().join("\n\n"));

If you looking for a good Javascript Date library, checkout moment.js.

More info:
MDN Date Object

Larry Battle

I love to program, and discover new tech. Check out my stackoverflow and github accounts.

More Posts - Website

Follow Me:
TwitterLinkedInYouTube