Dart for JavaScript Programmers

My perspective on Dart has quickly changed from being a language I needed to learn to build something with Flutter to a language I enjoy using on a daily basis.

dartlang-card

When starting with Flutter you often hear that Dart is just like JavaScript. Well, it is… except for when it isn’t. I thought it may be helpful to highlight some of the subtle ways in which Dart differs from JavaScript to make it easier to get up to speed when switching languages.

Conditions must have a static type of ‘bool’

In addition to types, Dart is in general a stricter language. In JavaScript you can use any ‘truthy’ value in a conditional. For example:

var name = 'Joe';
if (name) {
  // do something...

If you try the equivalent code in Dart you’d see “Conditions must have a static type of ‘bool'”. The reason is that Dart requires that a condition is a bool true not just a ‘truthy’ value. You could correct the code by changing it to:

if (name.length > 0)

But the preferred approach would be:

if (name.isNotEmpty)

Related to this, there is no triple equals (===) in Dart.

As a side note I saw this great tip on Twitter to use the same analysis_options.yaml as the Flutter team. It’s been a big help getting up to speed with Dart best practices in general.

Where is console.log

Although I’m constantly trying to train myself to rely on the debugger old habits die hard. In place of console.log you can use print. Dart supports string interpolation so whereas with JavaScript you may write:

console.log('Name is %s', name);

With Dart you’d use:

print('Name is $name');

If you need to access properties on the variable or call functions you can wrap it in curly braces.

print('Length is ${name.length}');

Function Parameters

This is one area where I think JavaScript and Dart are the most different. Dart provides a far more powerful implementation but it can take a bit of time to adjust to.

This answer on StackOverflow by Seth Ladd does a great job of explaining the differences in detail. At a high level with Dart you can either pass parameters in set positions:

getFullName('John', 'Doe');

Or you can pass them by name:

getFullName(firstName: 'John', lastName: 'Doe');

For constructors you can use this.fieldName to tell Dart that the value passed should be assigned to the property.

Contact(this.firstName);

Handling Arrays

Arrays are mainly the same but there are a few differences worth pointing out. A key difference is that you add an item to array by calling add rather than push.

Dart provides helper methods first and firstWhere which you may not be surprised to learn returns the first item in the array. What’s less obvious is that by default if a match isn’t found the methods will throw an error. You can handle this case by specifying a value for orElse which will be returned if no item is found.

Final and Const

This one took a while for it to sink in. I think this post does the best job explaining the differences that I’ve found. The key difference between final and const is that ‘final’ describes the variable whereas ‘const’ describe the value itself. A final variable can only be set once but the value it points to can be changed, a const’s value is frozen and can not be changed.

Another good tip you’ll get from using the Flutter analysis_options file is to use const constructors where possible when creating your widgets. This can have a great impact on your app’s performance by enabling the framework to cache the widgets.

Fat Arrow

The ‘Fat Arrow’ or => can be used for single line functions. For example, instead of:

someField: () {
  return true;
},

You could write:

someField: () => true,

It seems like a small difference but it can definitely have a positive impact on the readability of the code.

Odds & Ends

To wrap up here are a few other points worth keeping in mind.

  • To convert a value (for example) to a double you can either use double.parse or double.tryParse. The former will throw an error if it fails whereas the latter will not.
  • You can use null-aware operators (ie contact?.firstName) to make it easier to handle null values. This post (also by Seth) does a great job explaining it in detail.

Hope this helps, if anything’s unclear please let me know and I’ll update it.

 

6 thoughts on “Dart for JavaScript Programmers”

  1. Haha! Ignore my earlier comment. Misclicked…

    I was going to say that it’s actually not required to use `toString()` in your example: `print(error.toString());` If you write `print(error);` then Dart will call `toString()` will be automatically called on `error`.

    1. Thanks for correction! I’m pretty sure I’ve run into a toString problem while debugging but I’m having trouble replicating it now. I’ll update once I figure it out..

      Edit: I realize my problem, I was trying to use print(‘Error is: ‘ + error);

  2. I start to learn flutter and dart as freelancer yet I am having doubts that I can find any opportunities for it, for example only 18 job post on upwork.
    I am afraid that flutter may die on the other side telling myself that Google will support it to the end.

    1. That’s a good question…

      Google are a great company to have backing it but it isn’t like they haven’t given up on things in the past. I believe that with time more developers will become aware of how great the developer experience is with Flutter causing them to switch. As this happens there will be more jobs.

      Part of my confidence in Flutter is the understanding of how difficult it would be for another company to create something equivalent. I don’t believe we’ll see many jobs soon but over time think it will grow.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s