Thoughts from the Wet Coast

The musings of an ASP.NET Developer from Canada's We(s)t Coast

JavaScript for C# Developers: 3. The Dot Notation and the [] Notation

Category: JavaScript
Last Modified: May 2 2017
Aug 20 2015

Its been a while since I blogged in my series on JavaScript for C# developers, but I have got a few topics lined up.

As C# developers we are used to using the dot notation to access an object’s properties.  We are used to writing code like that shown in Listing 1.

Listing 1: Using the Dot Notation in C#

public class Person {     public string FirstName { get; set; }     public string LastName { get; set; } }  public class Application {     public static void Main()     {         var person = new Person();         person.FirstName = "John";         person.LastName = "Smith";     } }

The “.” indicates that the next item is a member of the previous item.  If the second item is a class then it would also have properties and methods and we can - in theory - go on forever.

JavaScript is similar in this respect.  We can write code that bears more than a passing similarity to the C# code in Listing 1.  This code is shown in Listing 2.

Listing 2: Using the Dot Notation in JavaScript

var person = { firstName: "", lastName: ""};  person.firstName = "John"; person.lastName = "Smith";

So we can feel comfortable that JavaScript and C# have similar approaches to access the members of an object.  There may be differences in how object’s are defined and created in JavaScript, but the logic to access members of the object is essentially the same.

However, JavaScript has a second method to access the properties - one that is quite powerful.  JavaScript objects can be thought of as property bags, each member can be accessed using the [] indexer notation.  The same code from Listing 2 has been rewritten in Listing 3 using this [] notation.

Listing 3: Using the [] Notation in JavaScript

var person = { firstName: "", lastName: ""};  person["firstName"] = "John"; person["lastName"] = "Smith";

Essentially an object in JavaScript is like a HashTable in C#, whose values can also be accessed using a dot notation style. 

I mentioned above that this can be quite powerful.  This is because an object’s property “names” do not need to be identified at design time.  I can access a property by using a variable as the index to the "array” of properties.  So code that requires complex Reflection in C# can be easily written in JavaScript.

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

Categories

Tags