Basic JavaScript arrays reminder

I’m pretty bad when it comes to remembering syntax details for languages I don’t use every day, especially since I work with a few languages that use C-syntax and not just JavaScript. Also, it’s not the kind of details I want to spend a lot of time studying since this information can easily be found.

In most cases, it’s easy to look up how something is done in the project you’re working on, since you’ll want to follow existing patterns anyway. But since I’m working on refreshing my JavaScript knowledge and trying new patterns, I’m often faced with a blank .js file. Arrays are always one of the first things that comes up when trying to solve a problem, so I thought a quick reminder could be useful.

A standard JavaScript array is most often initialized with the bracket notation. There is also an Array object, but using the Array() constructor is not totally identical to using the bracket notation since it’s an object in that case. To keep things simple I won’t be using the object since standard arrays are a lot more common.

var fruitsArray = [];

Inserting new items at the end of an existing array is done using the push() method. The array will resize to accommodate the new items. An array can also contain any items: it is not limited to one type.

fruitsArray.push("Tomato");
fruitsArray.push("Squash");
fruitsArray.push("Potato");
fruitsArray.push("Carrot");

Removing the last item at the end of an array is done using the pop() method. In the example, the “Carrot” item will be removed.

fruitsArray.pop();

Sorting an array is done using the sort() method. By default, the items are sorted as strings, so it works for the example. For more complex cases, a sort function can be passed as a parameter to the method.

fruitsArray.sort();

Looping in an array from the start to the end using the for loop, getting the items and printing them to the console. The example also shows the length property to get the current size of the array.

for (i = 0; i < fruitsArray.length; i++) { 
   console.log(i, fruitsArray[i]);
}

Checking if a variable is an array, printing the result to the console. This condition is useful when you can’t be sure about the type of a variable, for example because you received it as a parameter.

if (fruitsArray instanceof Array)
   console.log("fruitsArray is an array");
else
   console.log("fruitsArray is not an array");

Finding an item in an array using the indexOf() method. This method returns the index of the item in the array, or -1 if the item doesn’t exist.

var itemIndex = fruitsArray.indexOf("Carrot"); // Contains -1
itemIndex = fruitsArray.indexOf("Potato");     // Now contains 0

Finally, here are all the examples in one code snippet so you execute them and try for yourself :

var fruitsArray = [];

// Inserting items
fruitsArray.push("Tomato");
fruitsArray.push("Squash");
fruitsArray.push("Potato");
fruitsArray.push("Carrot")
console.log(fruitsArray); // ["Tomato", "Squash", "Potato", "Carrot"]

// Removing an item at the end of the array
fruitsArray.pop();
console.log(fruitsArray); // ["Tomato", "Squash", "Potato"]

// Sort the array as string
fruitsArray.sort();
console.log(fruitsArray); // ["Potato", "Squash", "Tomato"]

// Length of the array
console.log(fruitsArray.length); // 3

// Looping in an array, getting the items
for (i = 0; i < fruitsArray.length; i++) { 
   console.log(i, fruitsArray[i]);
}

// Check if a variable is an array
if (fruitsArray instanceof Array)
   console.log("fruitsArray is an array");
else
   console.log("fruitsArray is not an array");

// Search for an item in an array (returns the index)
console.log(fruitsArray.indexOf("Carrot")); // -1
console.log(fruitsArray.indexOf("Potato")); // 0

Review : Web tooling and automation course on Udacity

In the last few weeks, I’ve gone through a few courses on the Udacity since I’ve been looking to update my JavaScript skills. The Udacity courses are mostly videos, but short and to the point. I often have trouble following along with videos when they’re too long and would rather have the transcript, but it was not a problem with those courses. It’s easy to follow along, and there are often chances to try out the material immediately instead of having to watch an hour of video before doing anything.

The courses are also not as close to the format of a university course than Coursera or Edx: the focus is on a specific subject, such as testing JavaScript or responsive design. There is no extra fluff beside the main subject, so you need to listen to the basic courses in HTML and JavaScript if you don’t already have a background in it.

Also, I was able to go through the courses faster than the posted times in most of the case: it’s easy to squeeze in a few videos and an exercise when you have a bit of spare time.

The Web tooling and automation course was the best out of the ones I tried. The goal of this course is to showcase a good workflow for a web application based on JavaScript. Since I’ve mostly worked in a .NET/Visual Studio environment lately, I’m interested in learning about the latest best practices and tools in the JavaScript world. It’s rarer to see a course that focuses especially on this: I often default to following a beginner’s course to get this information since they’ll teach how to get setup, but it’s not always representative of what someone would do to build a large application.

The course covers the following subjects :

  • Advanced editor features: The best plugins and tools to make Sublime Text a great editor for the web. It’s as good as Visual Studio once properly setup for a fraction of the system resources, and a lot faster. I’m sold!
  • Managing builds with Gulp: How to automates steps like generating CSS from SASS, minification, bundling/concatenation and creating a release version. It’s a powerful tool, and it uses JavaScript so there was no need to learn a new syntax just for the build tool.
  • Setting up live editing in the browser: It’s not something I had considered doing before since most of my projects require a session and some form of authentication, but it’s interesting to avoid copy-pasting modifications from Firebug or the Chrome developer tools while working on a complex layout.
  • Linting and unit testing: The linting, or validating the JavaScript syntax was easy to setup, but I had trouble making the testing tools work on my Linux laptop. It was not the fault of the course material, and I was able to make it work after reinstalling a few packages.

The only problem is that the downloadable examples start with the solution to the first exercise instead of the scaffolding to fill in. It’s only annoying for the first lesson since all the exercise build on each other, so you won’t miss much.

In conclusion, you must do this course if you’re interested in JavaScript and want to improve your workflow. It’s a very small time investment for all the tricks and tools you’ll learn.

Using the jQuery UI datepicker with ASP.NET MVC

I wanted to start the real code for my side project by making a small skeleton of the project in ASP.NET MVC. This skeleton includes a basic form to create an event, which will be the starting point of the application. An event has a name with a start date and an end date that are represented as DateTime, so I figured I’d try my hand at integrating the jQuery UI datepicker to my form. That way, I’ll be able to make sure that jQuery UI is properly included in the application.

First, I included a bundle for the jQuery UI library along with jQuery on the page where I wanted the date picker to be.

After this, I created a input box using the TextBoxFor Razor helper which will be used to initialize the datepicker in JavaScript. I used the short date string so I would only get the date and not the time, and set the control as being read only so the user would be forced to pick the date from the picker. That way, I won’t have to handle the various date formats that could be entered.

<div>
   @Html.LabelFor(model => model.ScheduledEvent.StartDate)
      <div>
         @Html.TextBoxFor(model => model.ScheduledEvent.StartDate, 
                          new { Value = Model.ScheduledEvent.StartDate.ToShortDateString(),
                                @class = "datefield", 
                                @readonly = "readonly" })
      </div>
</div>

After this, I added the following to the JavaScript for my page to initialize the jQuery UI datepicker when the page is loaded.

$(document).ready(function () {
   $(".datefield").datepicker();
});

This already looked good when the page was first loaded, but there was a bug when a date was selected in the picker: the format of the date was not the same. Here is how it looked like with the original start date and the end date that was modified by the date picker:

AfterDatepicker

It works for saving the date, but it doesn’t look very good so this has to be fixed. But why is the format wrong? Well, my development machine is currently set to the fr-CA culture. ASP.NET MVC understands the fr-CA culture just fine and renders the dates in the format specified for that culture. On the client side thought, jQuery UI does not include the localization file to handle the date format for this culture by default, so it fallbacks to a standard format when setting an new date.

Fortunately, the fix is simple: you must set a default culture in you Web.config that jQuery UI can understand, which is en-US if no localization file is included. That will also make sure that you have the right culture in ASP.NET too regardless of the current culture of the server the application is executing on.

<system.web>
   <globalization uiCulture="en-US" culture="en-US" />
</system.web>

If you want to handle other cultures you must download and use the localization files from the jQuery UI at https://github.com/jquery/jquery-ui/tree/master/ui/i18n. For my project, I decided to force everything to en-US for now since the date format should be the same regardless of the culture of the browser of the user. This is to avoid confusion if multiple users with browsers set to different cultures are using the application to plan an event together.

A few closing notes

Don’t set the type of the input text box to the HTML5 date format, leave it as a standard text box. Otherwise, Chrome will use its own format for the date and you will get the following error when posting the form:
The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.

I also looked for the problem in the wrong place for quite a while: I usually submit values to WebAPI instead of submitting an ASP.NET MVC form, and WebAPI uses a different parser for dates.