Appcelerator Blog

The Leading Resource for All Things Mobile

Beginners: Javascript Objects and Arrays

5 Flares 5 Flares ×

If you’re new to Titanium, first of all Welcome!

If you are just starting out with Javascript, this post will definitely help you understand two very important features of Javascript: Object and Array literals. Knowing their syntax will not only help you understand how Titanium works, but will speed up your understanding of CommonJS and JSON.

Perhaps you don’t know them by name, but the truth is that when you work with Javascript, you’re working with Objects all the time without realizing it. Take a look at the following example:

var carmake='Honda';
console.log(carmake.toUpperCase());

Where did toUpperCase come from? Here you have used an Object. Every time you create a String variable, you’re actually creating a String Object. This object has properties and methods, toUpperCase being just one of them. More details about the String object here. Get used to the word “Object”, because is the foundation of modern programming.

Object Literals

Object Literals are Objects that you create on the fly. The syntax for Object literals is simple:

  • Enclose it in curly brackets
  • separate properties with comma
  • separate keys and values with a colon

var person={
    name: 'jack',
    email: 'jack@ctu.com',
    twitter: '@jackb_ctu'
};

To access the values on this object, you can use “dot notation”, that is, the name of the object, a dot, and the name of the property.

console.log(person.name);
console.log(person.twitter);

Array Literals

Just like objects, arrays can also be created on the fly. The syntax rules for array literals:

  • Enclose it in square brackets
  • separate each element with comma
var arr=[
            'value1',
            'value2',
            'value3'
        ];

To access the values, you use a numerical index:

console.log(arr[0]);

The fun part

The power of Javascript Object and Array literals comes by combining them. A combination of Objects and Arrays make up a complex, multidimensional object.

Array literal with two objects as values

var arr=[
           {key1:'value1'},
           {key2:'value2'}
        ];
console.log(arr[0].key1);

Object literal with a two-item array as property

var obj={
            key:[
                   'value1',
                   'value2'
                ]
        };
console.log(obj.key[1]);

Array literal with one property that is a two-item array

var arr=[
           {
              key:[
                    'value1',
                    'value2'
                  ]
            }
         ];
console.log(arr[0].key[1]);

This syntax is very popular in today’s web services and perhaps you’ve heard of JSON (Javascript Object Notation). JSON is an implementation of this syntax designed to be a way of transporting data across the Internet.

Applying these concepts in Titanium

Titanium itself is a JavaScript SDK (Software Development Kit) that works as an “Object Factory”. This means that it has methods that generate Objects, and most of the times these methods receive Objects as arguments. It sounds more confusing than it is.

var win=Titanium.UI.createWindow({
    backgroundColor: '#fff',
    fullscreen: true
})

The result of this operation is a Titanium Window Object stored in the variable win. However, the createWindow method received an object as argument, and object with the properties backgroundColor and fullscreen. As you can see, knowing how an object is constructed allows you to understand that the createWindow() and the toUpperCase() methods are very similar. The difference is that you are sending an Object Literal to the createWindow method.

A full description of Titanium’s objects can be found at Titanium API Documentation.

I hope this short tutorial can help you understand Titanium’s syntax and how powerful it can be.

Codestrong!

5 Flares Twitter 0 Facebook 0 Google+ 5 LinkedIn 0 Email -- 5 Flares ×

7 Comments

  1. Hi Ricardo Alcocer,

    I have a question, I can access lab.font.fontSize of a label. But, I can’t set using same font.fontSize = ’18sp’;
    What was the reason?

    And also If I did not put font property in Label style properties. And trying to set font.fontSize = ’18sp’ It showing error. I understand because font is
    undefined.

    Thank you,
    Naga Harish.

    Thank you,
    Naga Harish.

    • Ricardo Alcocer

      @Naga Harish,

      This has to do with the way Titanium Proxy Objects work. This post explains it in detail.

      R

  2. Excellent intro.

  3. @Naga

    Font is itself an object – a nested object referred to in the blog post. The relevant part of the post Ricardo linked is this:

    //doesn’t work
    l.font.fontSize = 24;

    //this does work
    l.font = {
    fontFamily:’Trebuchet MS’,
    fontSize: 24
    };

    Hope that helps.
    -m

  4. Denis

    Hello, I wonder if it is possible to:
    I have a textarea where I want to enter multiple numbers separated by a comma and then perform the average from an average function, the sintazis I’ve used is as follows:

    function average(){
    var n = document.calc.visor.value;
    var x=newArray(n);
    var sum = 0;
    for(var i=0;i<x.length;i++){sum=sum+x[i];}
    document.calc.result.value = sum/x.length;
    }

    HOWEVER not how to take the array for textarea values ​​and then perform the average when you press the button.
    Or how could I do otherwise but entering values ​​in textarea.
    Thanks and regards.

  5. Ricardo Alcocer

    @Denis,

    The best place to ask this type of question is the Q&A Forums @ http://developer.appcelerator.com/questions/newest.

    The function you’re trying to use is based on the DOM or the browser, and that won’t work because there’s no DOM in Titanium. You’ll have to rewrite it something like this:

    function average(value){
        var x=value.split(',');
        var sum = 0;
        for(var i=0;i<x.length;i++){
          sum=sum+x[i];
        }
        return sum/x.length;
    }
    

    And to call it:
    console.log(average(‘1,5,2,3’));

    The contents of a Text Field can be accessed via the “value”
    property (http://docs.appcelerator.com/titanium/3.0/#!/api/Titanium.UI.TextField-property-value).
    This means that if your text field is called “numbers”, you’ll do something like:

    average(numbers.value);

    Hope this helps!

    R

  6. Denis

    Thank you.

Comments are closed.

Sign up for updates!

Become a mobile leader. Take the first step to scale mobile innovation throughout your enterprise.
Get in touch
computer and tablet showing Appcelerator software
Start free, grow from there.
5 Flares Twitter 0 Facebook 0 Google+ 5 LinkedIn 0 Email -- 5 Flares ×