I haven't done a lot of coding in dynamically typed languages such as JavaScript until recently, and now that I'm beginning to understand what's possible, I'm starting to wonder what's a good idea and what's not. Specifically, I am unsure as to whether changing the type of a variable as a function progresses through a sequence of operations is considered good practice.
For example, I have a bunch of files containing dates as strings. I'm using front-matter to extract date attributes and storing them within an object representing the original file. The strings themselves aren't very consistent, so I'm then using Moment.js to parse them, and storing the result back in the same attribute in the same object article.date
. This feels more or less right to me, as article.date
is only a String for one operation before being parsed and stored as a Date/'Moment' type.
The part I'm a little unsure of comes next. This is part of an ExpressJS app, and so an array of these objects is getting passed in as the data in a render() call, where it goes to a Jade template for rendering. But what if I want to use a display method in Moment.js to control the way the date looks as a String? Would it be reasonable to change the type of the date attribute back to a String again before passing it in?
Example:
articles[i] = processArticle(content);
// creates an article object from YAML, object has a property article.attributes.date
articles[i].attributes.date = moment(articles[i].attributes.date);
// attribute is now a Date/Moment
articles[i].attributes.date = articles[i].attributes.date.format("dddd, MMMM Do YYYY, h:mm:ss a");
// attribute is now "Sunday, February 14th 2010, 3:25:50 pm"