JS Language

This chapter will not give you a general introduction to JavaScript. There are other books out there for a general introduction to JavaScript, please visit this great side on Mozilla Developer NetworkJS Language - 图1 (opens new window).

On the surface JavaScript is a very common language and does not differ a lot from other languages:

  1. function countDown() {
  2. for(var i=0; i<10; i++) {
  3. console.log('index: ' + i)
  4. }
  5. }
  6. function countDown2() {
  7. var i=10;
  8. while( i>0 ) {
  9. i--;
  10. }
  11. }

But be warned JS has function scope and not block scope as in C++ (see Functions and function scopeJS Language - 图2 (opens new window)).

The statements if ... else, break, continue also work as expected. The switch case can also compare other types and not just integer values:

  1. function getAge(name) {
  2. // switch over a string
  3. switch(name) {
  4. case "father":
  5. return 58;
  6. case "mother":
  7. return 56;
  8. }
  9. return unknown;
  10. }

JS knows several values which can be false, e.g. false, 0, "", undefined, null). For example, a function returns by default undefined. To test for false use the === identity operator. The == equality operator will do type conversion to test for equality. If possible use the faster and better === strict equality operator which will test for identity (see Comparison operatorsJS Language - 图3 (opens new window).

Under the hood, javascript has its own ways of doing things. For example arrays:

  1. function doIt() {
  2. var a = [] // empty arrays
  3. a.push(10) // addend number on arrays
  4. a.push("Monkey") // append string on arrays
  5. console.log(a.length) // prints 2
  6. a[0] // returns 10
  7. a[1] // returns Monkey
  8. a[2] // returns undefined
  9. a[99] = "String" // a valid assignment
  10. console.log(a.length) // prints 100
  11. a[98] // contains the value undefined
  12. }

Also for people coming from C++ or Java which are used to an OO language JS just works differently. JS is not purely an OO language it is a so-called prototype based language. Each object has a prototype object. An object is created based on his prototype object. Please read more about this in the book Javascript the Good Parts by Douglas CrockfordJS Language - 图4 (opens new window).

To test some small JS snippets you can use the online JS ConsoleJS Language - 图5 (opens new window) or just build a little piece of QML code:

  1. import QtQuick 2.5
  2. Item {
  3. function runJS() {
  4. console.log("Your JS code goes here");
  5. }
  6. Component.onCompleted: {
  7. runJS();
  8. }
  9. }