WHAT'S NEW?
Loading...
Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Index

  • Intro
  • History
  • Books
  • Videos
  • Frameworks
  • Others
  • References

Intro


More and more this language is being popular to the point we can even use it all along the whole stack of our apps. A new JS framework has been released while you read these lines. This is something that makes me want to learn JavaScript. Here I enclose a bunch of resources that I'll be updating during time. I think you can find useful to start learning JS, or at least, confirm what you know about it.

History

JavaScript was originally developed in 10 days in May 1995 by Brendan Eich, while he was working for Netscape Communications Corporation.

Although it was developed under the name Mocha, the language was officially called LiveScript when it first shipped in beta releases of Netscape Navigator 2.0 in September 1995, but it was renamed JavaScript when it was deployed in the Netscape browser version 2.0B3.

In November 1996, Netscape announced that it had submitted JavaScript to Ecma International for consideration as an industry standard, and subsequent work resulted in the standardized version named ECMAScript.

ECMA (European Computer Manufacturers Association) is a non-profit international institution who takes care of building standards in computer systems. It eases the building and communication between languages by creating standards used in: C#, C++, XML, JSON, JavaScript, JScript (Microsoft), ActionScript (Adobe Flash)...

The standard used by JavaScript is called ECMAScript and these are the different versions released by ECMA:

  1. In June 1997, Ecma International published the first edition of the ECMA-262 specification. 
  2. In June 1998, some modifications were made to adapt it to the ISO/IEC-16262 standard, and the second edition was released. 
  3. The third edition of ECMA-262 was published on December 1999.
  4. Development of the fourth edition of the ECMAScript standard was never completed.
  5. The fifth edition was released in December 2009
  6. The current edition of the ECMAScript standard is 6, released in June 2015.

Books

JavaScript, the good parts: This book is considered a MUST to have in your library. It was written by the PayPal engineer Douglas Crockford in 2008 and although it's small book, it will give you the very fundamentals you will need in order to continue learning more advanced stuff.



Videos

This Douglas Crockford's YouTube list contains around 80 videos where you will find out how the language evolved, who is Douglas or how the future of the language will be.

Frameworks


  1. NodeJS: created by some Google's engineers on top of the V8 engine, it's a powerful tool as its main features are: 
    1. Use non-blocking
    2. Event-driven I/O to remain lightweight 
    3. Efficient in the face of data-intensive real time apps.
  2. AngularJS: some people say this platform brought order to the development in JS. It worth to know how it works and understand its benefits: single page application, controller approach...
  3. ReactJS: created by Facebook in order to bring statefull and richful controllers to the Web.
  4. MEAN: Full JavaScript stack built with MongoDb, ExpressJS, AngularJS and NodeJS. Best way to learn is doing: try this tutorial to build a Google Maps.
  5. jQuery: it's a fast, small and feature-rich JS library.


Others

References


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
The multimedia content is very important in web, you can use several plugins like Adobe Flash or Microsoft Silverlight to draw what you want, but these are proprietary components and the idea in HTML5 is to bring enough tools to the developer to be able to do it native in the browser. In this post we are going to talk about the Canvas element. This new tag provided by HTML5 allows you to add a region in your website to draw whatever you want. We need to add the canvas tag inside the <body> part and define the dimensions an id because we will use JS to. We can write a text between the open and close tags to show it when the browser can’t render our drawing. If you don't add the dimensions attributes then a canvas 300x150 will be created. Here an example:


     Alternative content to canvas element.




Once we have declared the element in our html file we need to draw something using JS. Here I enlcose some code to draw a line inside the canvas.

    
function draw() {
        var canvas = document.getElementById("board");
        if (canvas.getContext) {
            var context = canvas.getContext("2d");
            context.beginPath();
            context.moveTo(10, 10);
            context.lineTo(100, 100);
            context.stroke();
        }
    }
    window.onload = draw;

In this new post I want to focus on forms made by HTML5 and the new native functions provided to validate them. This does not mean that we don't need to validate the input written by the user in the server, but is a first filter. HTML5 provides you the way to create forms in an easier way: you can declare required fileds, specific data types like dates or emails and new components like date time pickers, progress bars, color selectors and everything without using javascript.

For your input tags you can declare several new "type" property like:
  • type = "search": specific text field for searchs. Actually is more an aestetic improvement rather than a new feature.
  • type = "tel": is a text box for phone numbers. Indeed, HTML allows you to write numbers and letters but some browsers show a numeric interface for phone numbers.
  • type = "email": specific control for email addresses.
  • type = "color": customized control for color selection.
  • type = "url": it allows you to write just URL addresses. It works in the same way as the "email" type.
  • type = "number": specific just for numbers, no letters. You can declare a "min" and "max" value to create a range for the user. The "step" attribute declare the increment or decrement each time.
  • type = "date" "time" "datetime" "datetime-local" "month" "local": all are prepare to control inputs related with dates and times. Just by showing a calendar.
  • type= "range": it's a flow control that represents a numeric value.
In this second part of our introduction to HTML5 we want to focus on main structural elements. We will use a classic blog to show you how to migrate your HTML&CSS code. The first thing "todo" is simple: say the browser you are using HTML5. We do it with the following tag at the top of our page: <!DOCTYPE HTML>. Much easier than older HTML and XHTML versions. Another important point if your site is not in english, is use the "lang" attribute in the <html> tag like here: <html lang="es"></html>. Finally, we need to declare the character definition used <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> or simply <meta charset="UTF-8">. Example:

<html lang="es">
   <head>
      <meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
   </head>
</html>

Back to HTML5 structural elements, just take a look to this blog. Is splitted (by <div> and CSS) in different parts: a header with the title of the blog, navigation with several links, content of each post (each post has also header, content, footer, comments,...), the footer at the end of the page... You can use <div> tag for everything you want. HTML5 adds new tags: header, footer, nav, article, section... to avoid use div for all. This doesn't mean you don't need div anymore, it is very usefull to add styles for example, but now, the browser knows what is the purpose of every section of the blog. In the image below you can compare HTML structural elements:



I want to start a chain of posts about the new features and how to use them in HTML5 and CSS3. You probably have heard about it, but maybe didn't read so much. These two elements are web standards for developers and they have arrived to replace (X)HTML 4.01 and CSS 2.1. Here the chapters of this course:



Still a beta, HTML5 and CSS3 have some new features you should know:

  • HTML5
    • New tags to represent some content in you web.
    • Delete tags without meaning because of CSS.
    • New elements to create animations or play sound or video without addins (Flash, Silverlight,...)
    • Form structure improvement and native validation
    • ...
  • CSS3
    • New selectors
    • Advanced design: round corners, gradients, multiple background images,...
    • HSL colour and oppacity
    • Fonts and WOFF format
    • Transitions, transformations and animations