WHAT'S NEW?
Loading...

JavaScript all you need to know about functions and arrays

Index


1. Introduction
2. Functions
3. Arrays


1. Introduction


Hi there, today I'd like to talk you about Javascript. I'm currently doing the Microsoft challenge: "Know it. Prove it", about web development and I found the javascript lesson very interesting for those who are not very familiar with this prototyping language.



Here I'd like to bring you a very practical post about how to create your own javascript methods and also give you a few examples about how to work with arrays and some of the most interesting methods we can use with this data structure.

2. Functions

In the following example I'll show you how to create a function (f1) and run it just when the page is ready and downloaded. Our function has no input parameters but it doesn't matter if we haven't defined any input arguments for the "f1" function. JS is clever enough to get those arguments we sent throw our function call and use them into the method "f1".

Besides, with the command "debugger" and the console open we stop the execution of javascript in the browser, and no error is triggered. If we type the word "arguments" in the browser console we will get a list with the five parameters defined in the function call.

app.onready = function (e) {

    f1("one", 2, 0.78, {}, {});

    function f1() {
        //function context
        debugger;
    }
}


This is an interesting example of how works the scope or visibility within functions and methods. Actually this two words refer to the same thing. The key point here is when we use the "ops" object here we are just able to see the add function but when we want to call the function "addNumbers" declared in the "ops" object we'll get an error because that function is not accessible.

If you remember previous posts about how classes work in OO language, this behaviour is called "Encapsulation". Don't get wrong, JS is not an OO language, so you won't have inheritance in your scripts for instance, JS is a prototyping language, which means, you can simulate classes but you don't have all the functionality from an OOP language.

var ops = {
    add: function addNumbers(n1, n2) {
        return n1 + n2;
    }
};
var x = ops.add(3, 5);  // x== 8
var y = ops.addNumbers(3, 5);   // not valid



In the following example you will see how scope works. We can't access the "y" value because it's declared inside the "someFunc" context. What we can do is call actually the function because it will return the value of the "y" variable. That's why our last code line works ok.

var x = 2000;
function someFunc() {
    var y = 12;
    return y;
}
var z = x + y;      // invalid use of y
var z = x + someFunc(); // z = 2012


This is just another example of how functions defined within functions are not visible from out of the main function. They are hidden for us if we try to reach them
from out of the main function.

function outerFunction(n) {
    function innerFunction() {
        return n*n;
    }
    return innerFunction();
}

var x = outerFunction(4);   // x == 16
// innerFunction cannot be called directly


Let's talk now about something called: Immediate functions (soft functions). This is used when you want a function be executed as soon as it is processed. Nothing really happens when you declare a function, the action comes whe you call the function.

(function() {...}());
or
(function() {...})();

A very typical example is one called "Module pattern": we can reach the getHiddenYear function because when the "mod" variable is processed, it is also executed and we get our mod
variable populated with the return of a function called getHiddenYear.

var mod = (function() {
    var m = 2000, c = 0, d = 10, y=2;
    return {
        getHiddenYear : function() {
            return m + c + d + y;
        }
    }
}());
var x = mod.getHiddenYear();    // x = 2012


This is a way maybe you are not so familiar. When we are calling a function without any parameters, we are actually passing the function into another method. In the example we are sending our function "add" into the "calc" function and in function "calc" we rename "add" into "processFuncCalc". It's a similar behaviour as delegates to say so.

function calc(n1, n2, processFuncCalc) {
    return processFuncCalc(n1, n2);
}

function executeMath() {
    setOutput(calc(4, 4, add));
}

3. Arrays

You are probably already familiar with arrays, if not, keep in mind arrays is kind of bunch of variables all of them grouped in the same array by a pair of square braces. Is like a big container for multiple values. Arrays have features like: simple declaration / instantiation. Here are some of the functions you can use with your arrays: pop, push, concat, map, filter, some, every, forEach, reduce, sort, splice, join, reverse.

Now I'd like to talk you about arrays and some power methods you can use in Javascript. First, please take a look at the following example where I show you the usage and output of those methods.

app.onready = function() {
    var fruit = ["apple", "banana", "orange", "berry" ];
    log(fruit); // apple banana orange

    fruit.push("pear");
    fruit.pop(); //bye bye pear

    fruit.slice(0, 1); // go to position 0 and take values until position 1.

    fruit.splice(1,2,"melon","orange"); 
    // starts on pos 1 (banana) taking banana and orange and inserting melon and orange

    fruit.map(function(i) { return i.toUpperCase(); }); 
    // all our fruits will be capital letters

    fruit.filter(function(i) { return i[0] === "a";});  
    // using filter we can validate all our fruits and 
    // print those which start with "a". If not the fuirt will be deleted from the list

    fruit.every(function(i) { return i[0] === "a";});   
    // returns false. Not all of the fruits start with "a"

    fruit.some(function(i) { return i[0] === "a";});   
    // returns true. At least one starts with "a"

    log(fruit.sort); // print array
}


Those were simple examples to see what are you able to do playing with a bunch of strings within an array.

Finally, to conclude my today's post I am going to talk you about objects. I know JS is not object oriented, I already told you that. But anyway, we can simulate objects.

app.onready = function(e) {
    // we use culry braces instead of [] as we did for arrays
    var dog1 = {};
    dog1.breed = "German Shepherd";
    dog1.bark = function () { log("woof"); };

    var dog2 = {
        breed: "German Shepherd",
        bark: function () {
            log("woof");
        }
    }
}

In this function we are creating two objects: dog1 and dog2. For dog1, first we create the object and then we throw a property called "breed" into the object and a method/function called bark. And this will work exactly in the same way we've been using in our previous examples, you just need to call the bark function in order to dog1 start barking like this: dog1.bark();

For dog2 we are getting exactly the same result but defining first the property and then the method at the same time.

That's all for today guys! I hope you enjoyed this one and I hope to see you next time.

4. References


JS Module pattern: http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html
Javascript: http://www.w3schools.com/js/
                  http://en.wikipedia.org/wiki/JavaScript

0 comments:

Post a Comment