Issue 6
Issue 6
DART
www.facebook.com/cravegyan
Editorial Note
Maulik Dave
Editor-in-Chief Amit Chaudhary Managing Director Maulik Dave Senior Editor Samarth Sevak Viral Chauhan Deputy Editor Paresh Prajapati Upendrasinh Zala Correspondent Arpan Jokhahar Tushar Vyas Shailesh Rohit Art Director Monarch Pandya Senior Designer Renu Sharma Office Address The Web Dream Plot No:568/1, Sector: 4C, Gandhinagar-382006
Introduction
When your friend asks you to write a small web app, it is like a lot of fun to create it and give him. But, that is limited only when the length of code is very small. JavaScript is of great use to type few lines of code. Now, your friend asks you again to create a web app which consists of thousand-line code. To write large amount of code is not a difficult task, but to modify and debug that large app can be nightmare, especially when you are working with your team. Dart (originally Dash) is an open source Web Programming Language developed by Google. It was released at the GOTO conference in Aarhus, 2011 October 10-12. Dart is Googles replacement for JavaScript and main focus is to provide the same set of tools that JavaScript does, only as power tools. It aims to enable developers to build more complex, high performance apps for the modern web. Using the Dart language, you can quickly write prototypes that evolve rapidly, and you also have access to advanced tools, reliable collection of libraries, and good software engineering techniques. Dart is intended to solve JavaScript problems (which, according to a leaked memo, cannot be solved by evolving the language). Even though Dart is not so called known language, it already has tools such as Dashboard which lets you to write and execute the code in the browser, Dart Editor which lets you create, modify, and run Dart apps, Dart Virtual Machine, the VM that allows you to run the
1 | CraveGyan | May 2012 | Issue VI
code on servers and also the Dart-toJavaScript compiler packed in the SDK enabling you to translate the dart code into the JavaScript that is easily executable on the latest web browsers. Dart may not change the existing languages , but it may improve the way developers write
the codes for web applications.
www.cravedevelopers.com
support multiple-inheritance, but the general consensus is that it causes more problems than it solves, so most OOP languages go for single-inheritance. Optionally Typed Most languages are either typed or not. JavaScript, for example, is not. When you define a variable, it will be without type. You can set it to a string, then to a number, and nobody will complain it. In contrast, Java is typed. Every variable must be declared with a type, such as string or int. And when a variable is typed, you cant put a different type of value into it. And if you tried calling a method that doesnt exist on that type, the compiler will raise an error, letting you know your mistake before you run your code. C and its variants are other typed languages, while Ruby and Python are not.
With snapshot, it started up in 60ms. When your Dart program is running in the Dart VM, it can see significant startup time performance improvements, thanks to snapshots. Isolates Dart supports concurrent execution by way of isolates, which you can think of processes without the overhead. Each isolates has its own memory and code, which cant be affected by any other isolate. The only way an isolate can communicate with other isolate is by sending messages. Isolates allow a single app to use multi-core computers effectively. Another use for isolates: running code from different origins in the same page, without compromising security.
Reified Generics It is a language feature that allows you to assign the data type to the item of a collection. For example, an array in JavaScript cannot guarantee that the objects it contains are of any specific type. However, generics allow you to specify that every item in an array. Snapshots Currently, browsers need to phrase a web apps source code before that app can run. Dart code can be snapshotted-all its state and code recorded at a certain point in time-which can speed up startup considerably. In initial testing, a web app with 54,000 lines of Dart code started up in 640 ms without snapshot.
3 | CraveGyan | May 2012 | Issue VI
tire platform for modern web developers. Language specification: The Dart language is very familiar, with a few new features such as optional typing and isolates. Libraries: Core libraries generally found in it are collections, date, and math, as well as HTML bindings, server-side I/O such as sockets, and even JSON. Compiler to JavaScript: You can compile Dart programs to JavaScript that can run across the entire web. Virtual Machine: It is built from the ground up to run Dart code natively. The VM runs on the command line for server-side applications,
www.cravedevelopers.com
and can also be embedded into browsers for client-side applications. Integration with Chromium: The Dart VM has been embedded into a build of Chromium, nicknamed Dartium, allowing native Dart applications to run without first being compiled to JavaScript. Dart Editor: The lightweight editor, complete with syntax highlighting and code completion, can launch your script in the VM or web app in Dartium. It can also compile your web app to JavaScript and run it in another browser.
To comment the
code, you can put forward double slash for single line comment and /* .*/ for multiple lines. Unlike other languages, you cant divide the code of one line into two, else you will get a compilation error. Below is the Dart editor example with its output.
Language Tour
A basic Dart Program Here, we start with the basic functionalities of Dart language. The below sample code demonstrates how the printable statements is declared.
main() { // Single line comment print(Welcome to CraveGyan); }
Variables Variables are references. The variable named name stores the reference to a String object with a value CraveGyan.
To write and execute the above code, you need an editor, that is provided on www.dartlang.org. You have two options, either download SDK (Software Development kit) or copy and paste it into their editor which will execute your code on their own server. First line, main() signifies the starting point of the code as found in other languages like C, C++. It is mandatory to write the lines of code If the variable is not initialized with any value, by default it is set to NULL. As we said earlier, variables are optionally typed, but we recommend you to define the type for every variable to ensure your code will always run. Adding types is a good way to clearly express your intent. Compiler helps you by providing early warnings for bugs.
4 | CraveGyan | May 2012 | Issue VI www.cravedevelopers.com
Built-in types Dart language provides several data types such as:
if both the strings are same. To perform this == equivalent operator is used. The attractive feature of string lies in its methods like startsWith, endswWith, add, addall .. etc.
main() { var fullName=Amit and Maulik; fullName.startsWith(Amit); // true fullNmae.endsWith(Maulik); // true var sb = new StringBuffer(); sb.add("Amit "); sb.addAll(["Maulik ", "Samarth "]); sb.add("Arpan ").add ("Monarch"); print(sb); }
Strings String is a collection of characters. To create a string literal, you can use single quote or double quotes.
The StringBuffer class is useful for concatenating strings efficiently. Numbers It has two data types called int and double. To create a multi-line string; use a triple quote with either single or double quotation marks. When a variable is assigned a floating point value, compiler treats as double automatically. You can see in the below example that variable a is automatically converted to double and b is an int.
Boolean Dart has a formal type, named bool. When Dart expects a Boolean value, if that value isnt true, then its false. Unlike in JavaScript, values such as 1 or non-null objects are not treated as true. For instance, consider the following code:
var name = 'Amit'; if (name) { print("You have a name!"); // prints in JavaScript, not in Dart }
Lists (also known as arrays) Array is a collection of homogeneous elements where linearity is maintained with index values. In Dart, elements are known as objects, so it is known as list of objects. The base index starts with 0.
In JavaScript, this code prints You have a name! because name is a non-null object. However, in Dart, the above doesnt print at all because name is converted to false because name!=true. Heres another example of code that behaves differently in JavaScript and Dart:
if (1) { print("JavaScript prints this line because it thinks 1 is true."); } else { print("Dart prints this line because it thinks 1 is NOT true."); }
You can also add an element to a list using the add() method:
Darts treatment of Booleans is designed to avoid the strange behaviors that can arise when many values cant be treated as true: what this means for you is that, instead of using code like if(nonboolean_value), you should instead explicitly check for values. For example:
6 | CraveGyan | May 2012 | Issue VI www.cravedevelopers.com
To remove elements from a list (reducing the size of list), use the removeRange() method. As shown in the example, removeRange(1,1) method removes second element from the list.
Maps In general, a map is an object that associates keys to values. Dart supports for maps is provided by map literals and the Map interface. Heres a sample Dart map: Iterating When you need to access each element in the list, you can use for, for in, or forEach(). Use for when you need the current iteration index.
var list = [1,2,3]; for (var x = 0; x < list.length; x++) { print('$x: ${list[x]}'); }
In map literals, other than string keys you can also have numeric keys using constructor.
Output:
var map = new Map (); constructor map[1] = "Hadoop"; map[2] = PHP map[3] = Java;
// use a Map
A map value can be object or null. If youre If you dont need the index, you can use for...in: looking for a key that isnt in map, you get a null in return. If you want to know the number of elements in the map, you can use .length() method. Other method is remove() method through which you can delete any element when the key is specified as an argument. Now, to copy from one map to another, Dart provides a constructor called Map.from(). Lets see an example:
www.cravedevelopers.com
You can pass a function as a parameter to another function. For example, in the below program we are filtering odd numbers from the predefined list numbers to oddNums.
Functions Functions are written for reusability of a code. It reduces the lines of code as well as enhances the performance of the program.
All functions return a value. If no return value is specified, the statement return statement returns null; is implicitly appended to the function body. Operators Dart not only provides the operators like other languages, but it also shows the power Here, string is a return type, say is a function name and name is an argument that we pass from calling statement say(Amit). When the function is called at runtime, argument is passed to the function and its displayed on the screen. If we need to return any value, => value is used instead of return keyword. The above code with a => can be written like: Lets see examples of each type of operators: Arithmetic Operators of redefining them which we call it as operator overloading in C++.
www.cravedevelopers.com
It also supports both prefix and postfix operators. See the below example for it:
Logical Operators You can invert or combine boolean expressions using the logical operators. There are basically three operators in this category and they are && (AND), || (OR), and !expr (NOT). Here, ++a means it will increase the value by 1 and then assign to variable a. a++ means, it will print the value first and then increase the value by 1. Same kind of operations will be done with minus operator. Operators That Can Be Overloaded Operators are just instance methods with special names. For example 2 + 4 invokes the +method on 2, with the argument 4 something like 2.+(4). This has couple of consequences: Equality and Relational Operators Dart possess same operators like other scripting languages but has is unique operator. As shown in the example, a is declared as an integer variable, now, when a is num print statement executed, compiler will return true because a is an integer which is a part of num. Same way, we have tested for the string in the next line where compiler return true answer as variable a is not a string.
Dart lets you override many operators. For example, if you define a Overload class, you might define a + method to add two Overloads For operators that work on two operands, the leftmost operand determines which version of the operator is used.
www.cravedevelopers.com
< [] ^ & * -
| / ~/ >= >> ==
Control Flow You can control the flow of your Dart code using any of the following structure:
If and else For loops While and do while Break and continue Switch and case
If and else
The only difference between two loop is that in while loop it will first check the condition and in the do while, it will print the value of variable b first and then checks the condition. Break and Continue Break keyword halts the loop and comes out Remember, unlike JavaScript, Dart treats all values that are not true as false. For Loops You can iterate with the standard for loop. from the nearest enclosing brace and continue keyword is useful when you want to exclude some part. As shown in the example, break keyword will allow compiler to print only 1 and 2 and continue will print all values of c except 3.
10 | CraveGyan | May 2012 | Issue VI www.cravedevelopers.com
Note: If you omit the break statement, compiler will generate an error. Exceptions Your Dart code can throw and catch exceptions. Exception are errors that signal something happened that was not expected. It provides an Exception interface and numerous predefined exception types. You can also create your own exceptions by extending the Exception interface. Some common exception that occur during the execution of the program are: Switch and Case Switch statements in Dart compare objects using ==. Remember to include a break statement at the end of each non-empty case clause to avoid fall-through. A default keyword can be brought into use when no condition is fulfilled. An example of user defined exception:
www.cravedevelopers.com
Its not always you know what type of error will occur during run-time execution of the program, so you can take the benefit of finally clause which commands the compiler to execute the code enclosed in its brackets anyhow. It is very useful in web applications when one has opened the connection of the database but forgets to close it which may bring about hackers to break into the system. So one can always write such essential code into it.
Here, object is a name of object of the class Crave. With the use of object we can have access to all the data of a class. As you can see name2 is not defined while creation of the class but we can assign it during execution through the object.
Constructor Its a method having same name as class name. It is also known as initialization method because in a rule when we want to assign a Class As we know that Dart is an object-oriented language like Java, it embraces the most useful feature called class. Class is a collection of objects whose properties and methods are defined in the class which it belongs to. Lets see an example where class Crave is defined with variables name and name2.
12 | CraveGyan | May 2012 | Issue VI
set of values at runtime we can use it. When constructor is called without any argument, it is known as empty constructor or default constructor and when the constructor receives at least one argument, then it is known as parameterized constructor. As shown in the below example, constructor is called to assign the value 10 to the variable b.
www.cravedevelopers.com
Visit our blog www.englishunlocked.blogspot.com to learn English and ask your queries on www.facebook.englishunlocked
It wont be wrong if I say Object-oriented programming is nothing without Inheritance. Inheritance is the process of using the data of already defined in the base class into the sub classes. In the above shown example, we are using the variables of class Crave using object of the class Gyan. Once the base class has been inherited by the subclass, all the methods and data can be accessed by the subclass.
Getter and Setters This methods provide read and write access to internal object state. When calling a getter or setter, omit the trailing parentheses. Define getters and setters using the get and set Inheritance class Crave { int b; Crave_method(int a) // Same name { b=a; } } class Gyan extends Crave { int c; Gyan(int d) { c=d; } } main() { var object = new Gyan(10); object.Crave_method(20); print(object.b); print(object.c); }
13 | CraveGyan | May 2012 | Issue VI
keywords. class Rectangle { num left, top, width, height; Rectangle(this.left, this.top, this.width, this.height); set right(num value) = value - width; } main() { var rect = new Rectangle(3, 4, 20, 15); print(rect.left); // 3 rect.right = 12; // It will call set method print(rect.left); // -8 } => left
www.cravedevelopers.com
With getters and setters, you can start with instance variables, later wrapping them with methods, all without changing client code.
class Overload { final int x,y; const Overload(this.x, this.y); Overload operator +(Overload v) { // overrides + (a + b) return new Overload(x + v.x, y + v.y); } Overload operator -(Overload v) { // overrides - (a - b) return new Overload(x - v.x, y - v.y); } Overload operator negate() { // overrides unary negation (-a) return new Overload(-x,-y); } String toString() => '($x,$y)'; } main() { Overload v = new Overload(2,3); Overload w = new Overload(2,2); print(v); // (2,3) print(-v); // (-2,-3) print(v+w); // (4,5) print(v-w); // (0,1) }
Interface Using the keyword interface, you can fully abstract a class interface from its implementation. That is, using interface, you can specify what a class must do, but not how it does it. Interfaces are syntactically similar to classes, but they lack instance variables, and their methods are declared without any body. Once it is defined, any number of classes can implement any number of interfaces. Interfaces are designed to support dynamic method resolution at run time. Normally, in order for a method to be called from one class to another, both classes need to be present at compile time so the compiler can check to ensure that the method signatures are compatible. This requirement by itself makes for a static and nonextensible classing environment. Interfaces are designed to avert this problem. They disconnect the definition of a method or set of methods from the inheritance hierarchy. Defining an interface
interface Hashable { int hashCode(); }
Use the interface keyword to define an interNote: If you try to override (minus) unary operator, then it will show an error, it allows you to carry out overriding on binary operators only. To override (minus) operator use negate keyword. In the above example, operator is a keyword which tells the compiler that whatever follows it, is method name and the values enclosed in brackets are its parameters.
14 | CraveGyan | May 2012 | Issue VI
face. Notice how, instead of having a method body ({..}), the interface just has a semicolon (;). Implementing an interface A class can implement one or more interfaces y declaring them in its implements clause and providing the APIs required by the interfaces.
www.cravedevelopers.com
For example:
class Point implements Hashable { num x, y; ... // required by Hashable int hashCode() { int result = 17; result = 37 * result + x.hashCode(); result = 37 * result + y.hashCode(); return result; } ... }
// // //
Generics Interface can be extended You can create an interface that builds on one or more interfaces. The new interface is called a subinterface, and all the interfaces it inherits from are its superinterfaces. Use the extends keyword to specify which interface (or interfaces) youre adding to. Heres an example of creating subinterface of Hashable:
interface HashablePoint extends Hashable { num x, y; }
As types are optional in Dart, you never have to use generics. You might want to, though, for the same reason you might want to use other types in your code. It makes easier to express the intent of the code. For example, if you intend for a list to contain only strings, you can declare it as List<String> (read it as List of String). That way of you, your fellow programmers, and your tools (Dart Editor) can detect that assigning a nonstring to the list is probably a mistake.
List<String> names = new List<String>(); names.addAll(['Crave', 'Gyan', 'Magazine']); ... names.add(42); // fails to add the number
www.cravedevelopers.com
Note: Technically, interfaces dont have instance variables such as x and y. What looks like an instance variable is really a shortcut
15 | CraveGyan | May 2012 | Issue VI
Another reason for using generics is to reduce code duplication. Generics let you share a single interface and implementation between many types. It is same as Templates in C++. For example, say you create an interface for caching an object:
interface ObjectCache { Object getByKey(String key); setByKey(String key, Object value); }
Now lets take a look of JavaScript code and Dart code and know how their implementation differs from each other.
Getting Started
Code Embedding
JavaScript
<script src='program.js'></script>
You discover that you want a string-specific version of this interface, so you create another interface.
interface StringCache { String getByKey(String key); setByKey(String key, String value); }
Dart
// Note: This will only work in Dartium (a build of // Chromium with Dart VM) <script type='application/dart' src='program.dart'></script>
Later, you decide you want a number-specific version of this interface.You get the idea. Generic types can save you the trouble of creating all these interfaces. Instead, you can create a single interface that takes a type as a parameter:
interface Cache<T> { T getByKey(String key); setByKey(String key, T value); }
// Also, you'll need this to kickstart the Dart engine. <script type='text/javascript'> if (navigator.webkitStartDart) { navigator.webkitStartDart(); } </script>
In this code, T is the stand-in type. Its a placeholder that you can think of as a type that a developer will define later. This is what Dart tells about itself and there are many things that you must know which you have to learn it from its website so as we cant cover up all the topics.
function main() { // To be used as the entry point,
Entry Point
JavaScript
// Not required.
www.cravedevelopers.com
but it must be // called manually. } main(); // Sometimes the entry point is written as an // anonymous function (function(){ // Code to be run automatically on execution })();
JavaScript
console.log('CraveGyan Magazine');
Dart
print('CraveGyan Magazine');
Dart
// REQUIRED.
Code Modularity
main() { // this is the entry point to the program }
Define a library
JavaScript
// No native implementation. // Consider require.js and AMD
JavaScript
<noscript> Your browser doesnt support JavaScript. </noscript>
Dart
// declares the following is in the animals library #library('animals'); class Dog {
Dart
<script type='text/javascript'> }
www.cravedevelopers.com
Use a library
JavaScript
var myName; // == undefined
JavaScript
// No native implementation. // Consider require.js and AMD
Dart Dart
#import('animals'); var fido = new Dog(); var myName; // == null int x; // == null // prefixes are supported to avoid namespace collisions #import('animals', prefix: 'pets'); var fido = new pets.Dog();
Hoisting
JavaScript
// JavaScript "hoists" variables to the top of // their scope. function: So the following
Variables
Create + Assign Value
JavaScript
var myName = 'Amit';
Dart
// Dart variables can be typed... String myName = 'Amit'; // but they don't need to be var myOtherName = 'Arjun';
// is equivalent to this function: function printName() { var name; console.log('Hello, ' + name); name = 'Maulik'; } printName();
Default Value
// Hello, undefined
www.cravedevelopers.com
Dart
// Dart does not hoist variables. The following // method will issue a compilation error of "cannot resolve name" printName() { print('Hello, $name'); // compilation error here var name = 'Amit'; }
Dart
var a = new List(); var a = []; var a = [1, 2, 3];
JavaScript
var a = ['apple', 'banana', 'cherry']; // returns the new length of the array a.push('donut');
Final Variables
JavaScript
// Not supported
Dart
final name = 'Amit'; // you can combine types and final final String name = 'Amit'; // Trying to reassign a final variable raises an error name = 'Maulik'; // ERROR: cannot assign value to final variable
// == 4 a.length // == 4 a.pop()
Dart
var a = ['apple', 'banana', 'cherry']; a.add('donut'); // == null
Collections
Arrays/Lists
JavaScript
var a = new Array();
19 | CraveGyan | May 2012 | Issue VI
Custom Sort
Dart
// Keys in Dart must be string literals var names = { 'one' : 'Amit', 'two' : 'Maulik' };
JavaScript
var numbers = [42, 2.1, 5, 0.1, 391]; numbers.sort(function(a, b) { return a - b; }); // == [0.1, 2.1, 5, 42, 391]
Accessing Values
Dart
var numbers = [42, 2.1, 5, 0.1, 391]; numbers.sort((a, b) => a - b); // == [0.1, 2.1, 5, 42, 391];
JavaScript
names.one // == 'Amit' names['one'] // == 'Amit'
Dart
// Values can only be 'get' or 'set' by using the square // bracket notation. does not work Dot notation
Appropriate Keys
JavaScript
var names = { one: 'Amit', two: Maulik' };
JavaScript
var names = { 'one': 'Amit', 'two': 'Maulik' };
20 | CraveGyan | May 2012 | Issue VI
Dart
var fruits = new Set(); fruits.add('oranges');
www.cravedevelopers.com
Strings
Interpolation
JavaScript
var name = 'Gyan'; var greeting = 'Crave ' + name;
Queues (FIFO)
var greetingPolish = 'Crave ' + name + 'Magazine'; element.style.top = (top + 20) + 'px';
JavaScript
var queue = []; queue.push('one:Amit'); queue.push('two:Maulik'); console.log(queue.length); // 2 var eventId = queue.shift(); console.log(eventId === 'one:Amit'); console.log(queue.length); // 1
Dart
var name = 'Gyan'; var greeting = 'Crave $name.'; var greetingPolish = 'Crave ${name} Gyan.'; // calculations can be performed in string interpolation element.style.top = '${top + 20}
Dart
// Queues are optimized for removing items from the head var queue = new Queue(); queue.add('event:32342'); queue.add('event:49309'); print(queue.length); // 2
Substring
JavaScript
'doghouses'.substring(3, 8) // == 'houses' 'doghouses'.substr(3, 5) // == 'houses'
Dart
'doghouses'.substring(3, 8);
www.cravedevelopers.com
JavaScript
'doghouses'.replace(/s/g, 'z') // == 'doghouzez'
JavaScript
var animals = 'dogs, cats, gophers, zebras'; var individualAnimals = animals.split(', '); // == ['dogs', 'cats', 'gophers', 'zebras'];
Dart
'doghouses'.replaceAll('s','z'); // == 'doghouzez'
Dart
var animals = 'dogs, cats, gophers, zebras'; var individualAnimals = animals.split(', ');
JavaScript
'racecar'.replace(/r/, 'sp') // == 'spacecar'
Dart
'racecar'.replaceFirst('r', 'sp'); // == 'spacecar'
Multi-line strings
JavaScript
var string = 'This is a string that spans\n' + 'many lines.\n';
JavaScript
// JavaScript has no built-in startsWith function String.prototype.startsWith = function(beginning) {
Dart
// Dart ignores the first new-line (if it is directly after // the quotes), but not the last. } var string = ''' This is a string that spans many lines.'''; 'racecar'.startsWith('race') // == true 'racecar'.startsWith('pace') // == false var head = this.substr(0, beginning.length); return head == beginning;
www.cravedevelopers.com
Dart
// Dart string objects have a built -in startsWith method 'racecar'.startsWith('race'); // == true 'racecar'.startsWith('pace'); // == false
Dart
var zero = 0; if (zero == 0) { print('use == 0 to check zero');}
Booleans JavaScript
Checking for empty string
var myNull = null;
JavaScript
var emptyString = ''; if (!emptyString) { console.log('empty strings are treated as false');}
Dart
var myNull = null;
Dart
var emptyString = ''; if (emptyString.isEmpty()) { print('use isEmpty()');}
JavaScript
Checking for zero
var myNaN = NaN; if (!myNaN) { console.log('NaN is treated as false'); }
JavaScript
var zero = 0; if (!zero) { console.log('0 is treated as false');}
www.cravedevelopers.com
Dart
var myNan = 0/0; if (myNaN.isNaN()) {
var char5 = '5'; // This comparison triggers type conversion number1 == char1 // == true
// 'triple equals' checks type and value letterA === charA // == true number5 === char5 // == false
JavaScript
var isUndefined; if (!isUndefined) { console.log('undefined is treated as false');}
Dart
var letterA = 'A'; var charA = new String.fromCharCodes([65]); // String defines equals() as 'same character codes in same order' letterA == charA // == true // However, the following is different than JavaScript
Dart
// Dart does not have a concept of undefined
var number5 = 5; var char5 = '5'; number1 != char1 // == true, because of different types
JavaScript
var letterA = 'A'; var charA = String.fromCharCode (65);
Functions
// JavaScript converts both values to the same type // before checking their value with 'double equals'. letterA == charA // == true // Similarly... var number5 = 5;
Function Definition
JavaScript
function fn() { - - - - - - return true;}
www.cravedevelopers.com
Dart
// Specifying the return type of the function // is optional in Dart.
JavaScript
var loudify = function(msg) { return msg.toUpperCase();}
Return Value
JavaScript
function fn() { return 'Hello'; } fn(); // == 'Hello' (function(){})() // == returns undefined
Dart
var loudify = (msg) => msg.toUpperCase(); loudify('Its Crave Gyan'); // ITS CRAVE GYAN
Optional Parameters
Dart JavaScript
// Like JavaScript, use the 'return' keyword in a function // definition to return a value. fn() { return 'Hello'; } fn(); // == 'Hello' function fn(a, b, c) { return c; }; fn(1) // == undefined fn(1, 2, 3) // == 3
Dart
// A function with no return value returns null. ((){})(); // == returns null fn(a, b, c) => c; fn(1); // ERROR: NoSuchMethodException fn(1, 2, 3); // == 3 // if the body of the function is returning a single expression, // this is the short form fn() => true;
25 | CraveGyan | May 2012 | Issue VI
// Dart specifies optional parameters with square braces fn(a, [b, c]) => c; fn('a'); // == null
www.cravedevelopers.com
Default Parameters
JavaScript
function send(msg, rate) { rate = rate || 'First Class'; return msg + " was sent via " + rate; } send('hello') // == 'hello was sent via First Class' send("I'm cheap", '4th class') //
Dart
// Dart does not support variable numbers of arguments
Iterators
For loop for lists
JavaScript
var colors = ['red', 'orange', 'green']; for (var i = 0; i < colors.length; i++) {console.log(colors[i]);}
Dart
send(msg, [rate='First Class']) { return '${msg} was sent via ${rate}'; } send('hello'); // == 'hello was sent via First Class' send("I'm cheap", '4th class'); // == "I'm cheap was sent via 4th
Dart
var colors = ['red', 'orange', 'green']; for (var i = 0; i < colors.length; i++) {print(colors[i]);}
JavaScript
function superHeros() { for (var i = 0; i < arguments.length; i++) { console.log("There's no stopping " + arguments[i]);} }
JavaScript
var fruits = ['orange', 'apple', 'banana']; // 'in' notation in JavaScript returns the // indices of the array, not the values
www.cravedevelopers.com
#Include
Your first step towards programming
Visit our blog www.hassinclude.blogspot.com to learn Programming and ask your queries on www.facebook.CodeInclude
Classes
Define
Dart
var fruits = ['orange', 'apple', 'banana']; // 'in' notation in Dart returns the element // of the list, not the index for (var fruit in fruits) { print(fruit);}
JavaScript
function Person() { this.name = null; }; Person.prototype.greet = function() { return 'Hello, ' + this.name; }
Dart
class Person {
JavaScript
var data = { }; for (var key in data) { console.log('key', key); console.log('value', data[key]);}
JavaScript
function Person(name) {
Dart
var data = { }; for (var key in data.getKeys()) { print('$key, ${data[key]}');} // Alternatively, the forEach loop is a method on a Map in Dart. data.forEach((key, value){ print('${key}, ${value}');});
this.name = name;};
Dart
class Person { var name; Person(name) { this.name = name; }
www.cravedevelopers.com
// shorter alternative class Person { var name; // parameters prefixed by 'this.' will assign to // instance variables automatically Person(this.name);}
JavaScript
var name = 'Bob'; name instanceof String // == true (!(name instanceof int)) // == true
Dart
var name = 'Bob';
Instantiate
JavaScript
var person = new Person();
JavaScript
document.getElementById('main')
Reflection
document.querySelector('#main')
JavaScript
var name = 'Bob'; typeof name // == 'String'
Dart
document.query('#main')
Dart
// There currently is no way to get the class of an // object. Reflection support coming soon.
JavaScript
document.getElementsByClassName ('visible')[0] document.querySelector('.visible')
www.cravedevelopers.com
Dart
document.query('.visible')
('[name="form"]')
Dart
Find one element by tag
document.query('[name="form"]')
JavaScript
document.getElementsByTagName ('div')[0] document.querySelector('div')
Manipulating DOM
Create an element
JavaScript Dart
document.query('div') var element = document.createElement('div');
Dart
Find many elements by tag
#import('dart:html'); var element = new Element.tag ('div');
JavaScript
document.getElementsByTagName ('div') document.querySelectorAll('div')
JavaScript Dart
document.queryAll('div') var element = document.createElement('p'); element.innerHTML = 'A quick brown <em>fox</em>.';
Dart
var element = new Element.html ('<p>A quick brown <em>fox</em>.</ p>');
JavaScript
document.getElementsByName('form') [0] document.querySelector
www.cravedevelopers.com
Catch an exception
JavaScript
element.appendChild(newElement);
JavaScript
try {
Dart
element.nodes.add(newElement); }
undefinedFunction();
catch(e)
{ if (e instanceof ReferenceError) { console.log('You called a function that does not exist'); } } finally {console.log('This runs even if an exception is thrown');}
JavaScript
element.parentNode.removeChild (element);
Dart
element.remove();
Dart Exceptions
Throw an exception
try {Math.parseInt("three");} catch(BadNumberFormatException bnfe) { print("Ouch! Detected: $bnfe");} catch(var e) {print("If some other type of exception");} finally {print("This runs even if an exception is thrown");}
JavaScript
throw new Error("Intruder Alert!!"); // or... throw "Intruder Alert!!";
JavaScript
element.addEventListener('click',
www.cravedevelopers.com
handleOnClick, false);
Dart
element.on.click.add (handleOnClick);
Dart
measure(fn) {Stopwatch watch = new Stopwatch.start(); fn();
return watch.elapsedInMs);}
JavaScript
element.removeEventListener ('click', handleOnClick, false);
CSS Classes
Add CSS Class
Dart
element.on.click.remove (handleOnClick);
JavaScript
element.className += ' new-class'; element.classList.add('new-class');
Timing
Schedule a future event
Dart
element.classes.add('new-class');
JavaScript
setTimeout(function() { }, 500);
JavaScript Dart
window.setTimeout(() { }, 500); element.className = element.className.replace(/ newclass/, '');
Dart
element.classes.remove('newclass');
JavaScript
function measure(fn) { var start = Date.now();
www.cravedevelopers.com
Math
Absolute Value
JavaScript
Math.parseInt('3') // == 3 Math.parseDouble('3.14') // == 3.14 Math.parseInt('three') // ERROR: throws BadNumberFormatException
JavaScript
Math.abs(-4) // == 4
Dart
-4.abs() // == 4
Ceiling
define the language of the script. For Dart, this attribute has the value application/dart. Like other script tags, the script contents can be inlined as the body of the script tag or specified reference via a URL using the script tags src attribute. The Dart script must have a visible top-level function called main(), either declared directly in the script or in a sourced/imported file. The browser will invoke main() when the page is loaded. Fundamental differences from JavaScript Every HTML page can have multiple Dart script tags, but each Dart script tag in a page runs in isolation. This fundamentally differs from the way that JavaScript is embedded in HTMLin JavaScript, declaration across multiple script tags are combined together in the same namespace. In Dart, code in one script tag cannot directly access code defined in another. If a script wishes to load code from a different URL, it must do so via #source or #import. Each script tag must define its own main() entry point in order to run.
www.cravedevelopers.com
JavaScript
Math.ceil(4.89) // == 5
Dart
4.89.ceil() // == 5
Floor
JavaScript
Math.floor(4.89) // == 4
Dart
4.89.floor() // == 4
JavaScript
parseInt('3') // == 3 parseFloat('3.14') // == 3.14 parseInt('three') // NaN
Examples: Here is a simple Hello World in HTML using Dart. This script defines its own isolate/ library. The main() method is implicitly the entry point.
<html> <body> <script type='application/ dart'> void main() { HTMLElement element = document.getElementById ('message'); element.innerHTML = 'Hello from Dart'; } </script> <div id='message'></div> </body> </html>
References
1. Dart (Programming Language). (en.wikipedia.org/wiki/Google_Dart 2. Dart language hits Chrome test version. (http://www.ubergizmo.com/) 3. The chromium Blog. (http:// www.blog.chromium.org/) 4. Gilad Bracha: Dart-A Well Structured Web Programming Language. (http:// www.channel9.msdn.com/Events/Lang-NEXT) 5. Extreme Tech (http://www.extremetech.com/ GoogleDartUnveiled:Farewell,JavaScriptExtremenTech.htm) 6. Stack Overflow (http:// www.stackoverflow.com/ GoogleGoVSGoogleDartStackoverflow.htm) 7. Wired.com (http://wired.com/
To incorporate external code, use #source or #import directive instead. For example, suppose the file Hello.dart defines the hello() method.
<html> <body> <script type='application/ dart'> #source(Hello.dart) void main() { hello('Hello from Dart'); } </script> <div id="message"></div> </body> </html>
GoogleThrowsNewDartProgrammingLanguageAtTheWeb/) 8. Dart Structured Web apps (http:// www.dartlang.org/) 9. HTML Goodies (http:// www.htmlgoodies.com/) 10. O Reilly (http://www.radar.oreilly.com/) 11. Activetuts (http://www.active.tutplus.com/)
www.cravedevelopers.com
Visit our blog www.GyanKirti.blogspot.com to know facts of world and ask your queries on www.facebook.GyanKirti.GK