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

Windows services ON/OFF?

Index

  1. Introduction
  2. The batch file
  3. Configuring Server Side Includes (SSI)
  4. Showing the services status
  5. References

1. Introduction

Last week, someone asked me to provide the status in a web site of some of the services running on the server. The site is a simple html document with links to other pages, but the idea was to show for each of those links, the service status which is running on the server. It's something you can't do with javascript, because as you know, JS runs on the client. I needed a solution, but I didn't want to redo the web in ASP or PHP...



To solve it, I created the following (different approaches will be recognized): first, I am going to create a batch file, which once is executed will create a "txt" file with the status of the services I need to verify. In the text file I'll save if the service is running or not. On the other hand, I need my website to check that file somehow and provide those statuses in the front-end. For that point, I used "Server Side Includes" aka SSI. This is a technology you can use in different platforms like IIS, PHP, ... which allows you to add some especial tags in your HTML and with that, you can include text files or even execute files. Something really handy believe me.


2. The batch file

This is a really easy batch file which checks the status of a particular service and saves it on a file. Notice the way we save text in the file the first time and the others. The first time we use just one ">", this way we replace the content of the text file. This way we assure there is no information from previous executions.

@echo OFF



sc query "MWMService" | FIND "STATE" | FIND "RUNNING" >nul

IF ERRORLEVEL 1 (echo|set /p=[["Master","OFF"],> statuses.txt ) 
ELSE (echo|set /p=[["Master","ON"],> statuses.txt)



sc query "MWMService CGG" | FIND "STATE" | FIND "RUNNING" >nul

IF ERRORLEVEL 1 (echo|set /p=["CGG","OFF"],>> statuses.txt ) 
ELSE (echo|set /p=["CGG","ON"],>> statuses.txt)



sc query "MWMService CGA" | FIND "STATE" | FIND "RUNNING" >nul

IF ERRORLEVEL 1 (echo|set /p=["CGA","OFF"],>> statuses.txt ) 
ELSE (echo|set /p=["CGA","ON"],>> statuses.txt)



sc query "MWMService CGH" | FIND "STATE" | FIND "RUNNING" >nul

IF ERRORLEVEL 1 (echo|set /p=["CGH","OFF"],>> statuses.txt ) 
ELSE (echo|set /p=["CGH","ON"],>> statuses.txt)



sc query "MWMService CGI" | FIND "STATE" | FIND "RUNNING" >nul

IF ERRORLEVEL 1 (echo|set /p=["AGI","OFF"]];>> statuses.txt ) 
ELSE (echo|set /p=["AGI","ON"]];>> statuses.txt)



The output of this bat file is:

[["Master","OFF"], ["CGG","ON"], ["CGA","OFF"], ["CGH","ON"], ["AGI","ON"]]; 

As you can see we have ON/OFF depending on the status of each of those services. The other important part is the format, how we get it, because it can be used directly as a javascript array. We will see in the following chapter how to do this.

3. Configuring Server Side Includes (SSI)

First, you probably will need to install this feature on your server. You can follow this link here, provided by the guys from iis.net, but no worries, the steps are really simple. In my case, I was using an Internet Information Server 8:


  • On the taskbar, click Start, point to Administrative Tools, and then click Server Manager. 
  • In the Server Manager hierarchy pane, expand Roles, and then click Web Server (IIS). 
  • In the Web Server (IIS) pane, scroll to the Role Services section, and then click Add Role Services. 
  • On the Select Role Services page of the Add Role Services Wizard, select Server Side Includes, and then click Next. 
  • On the Confirm Installation Selections page, click Install. 
  • On the Results page, click Close.


Once the SSI is installed on your server, the next step it's just add it in your server mappings. So open your IIS instance and double click on "Handler Mappings", then click on "Add Module Mapping" and provide the following information:

Request Path: *.html
Module: ServerSideIncludeModule
Executable: blank
Name: SSI-html

4. Showing the services status

At this stage, we have everything prepared to start using SSI tags in our website. For example, you can use the following command inside of your html file to include the content of a file called test.txt



This way is really easy to save the content of that file in a javascript array and show the content wherever we want in our web page. See in this example how we use jQuery to replace some <div> tags in our web with the content of the file:

        $( document ).ready( function () {
            var items = 

            $("#Status1").replaceWith(items[0][1]);
            $("#Status2").replaceWith(items[1][1]);
            $("#Status3").replaceWith(items[2][1]);
            $("#Status4").replaceWith(items[3][1]);
            $("#Status5").replaceWith(items[4][1]);
        });

The array "items" will be populated previously by the server when the page is sent to the client. Once the page gets to the client, javascript will replace the content of our divs for the values in the array. This way we are accessing the windows services status directly.

I've been trying to find a way to run the bat file every time the page is loaded using the exec command from SSI but it has been impossible. Probably because of user rights. Anyway, as a walkaround. you can create a scheduled task running every minute to have the information updated.

I hope you enjoyed this post, please remember your opinion is really important for me to improve this blog. Looking forward to hear from you guys.

5. References

  • Activate SSI: http://www.iis.net/configreference/system.webserver/serversideinclude
  • Add mappings for SSI: http://tech.mikeal.com/blog1.php/server-side-includes-for-html-in-iis7