Category Archives: JavaScript

What is Functional Programming?

This question can be answered in many ways, let’s start with the basics of functional programming.

  • The “Functional Programming” is a one of the “Programming Paradigm”. whereas some other programming paradigms are “Imperative programming” and “Object Oriented Programming”.
  • Functional Programming is a paradigm where functions are kings, it is one of the ways in which we can approach any task or the problem.
  • Functional programming (often abbreviated FP) is the process of building software by composing pure functions, avoiding shared state, mutable data, and side-effects.
  • FP is declarative rather than Imperative and application state flows through pure functions.
  • Functional code tends to be more concise, more predictable and easy to understand than the imperative or oop.

There are a lot of people and libraries out there to help you out with the functional programming.

The idea of functional programming is to express everything in terms of functions.And a function is, of course, a function that takes an input and gives an output.

So, we have to think about how the data flows through the various functions rather than thinking about how the objects interact.

Let’s see the following example which is non-functional

So, if we look at the above code, we can say that it is the imperative style of programming where we execute step by step.We have no functions in the above code.

Let’s see the functional way of doing this

So, there is a more functional way of programming where we have a function which takes an input and return’s a string with the name and message.

The functional programming avoids the side effects by using the functional programming.

So, what do we mean by side effects, well if a function takes an input and returns the output which is not according to the input.

If any functions which are taking anything from outside the function and involving it inside the function that is not the pure functions.

The idea of pure functions is it should return the same output for every same input. For instance, if u pass 2 and 3 in function for doing sum it should return 5.

Let’s see the below example which is not a pure function.

In the example, as we can see that we are involving a global variable called “name” inside the function, it should not be considered as a pure function.

So, how the pure function for above code looks like let’s see the below code :

The function returns the output based on the input we have passed.

We can also have Higher order functions where we pass one function to another and so on.

Let’s see the below example :

The above function returns another function and both the functions are taking one input parameters each and returning the full name.

These type of functions are called Higher order functions where one functions can return one or more functions.

Avoiding Iterations:

So, other things which we are going to avoid are the iterations like for, if etc., we will using something like map, reduce, filter kind of terminology.

The idea here is we have a list of vegetables and we have to transform it in some or other way and make a sandwich.

Let’s see we have vegetables and we have a slice functions where we are slicing all the vegetables which we can apply to all list of items.

Here we are mapping all the list items and let’s say we have a chop functions where we are slicing all the vegetables and returning back from chop function.

Then, we have something called reduce where it will combine all the chopped items layer by layer and make a sandwich.

We also have a filter function, it comes into play when let’s say u hate cucumber and u don’t want it into your sandwich so the filter will help u to prepare your sandwich without cucumber.

So, the above examples show how we transform our list using map, reduce, filter technique.

Avoiding Mutability:

These are the another concept where we avoid mutation of data.

Mutation will be considered as a non-functional, let’s see the below example

So, these are called mutation, here we are doing modification in the original list.

If we modify the original list it will cause lot issues or bugs, the reason is the above array might have used at multiple places in real time programming.

This is one of the most important reasons why functional programming avoids mutation in the data.

So, instead of changing the original array how to add the room D? let’s see

Instead of modifying the original data we have created a new array and added a room called ‘D’ in a newRooms array.This is the one of avoiding the data mutation.

So, if we look at the above example we can see that copying array is not the solution for our problem it will cause a lot of efficiency issues in the real time.

we cannot go and copy the array every time, processing array is not the solution, it will cause a lot of memory wastage and we have to process all the elements in the list.

One way of avoiding the above issue is by using the persistent data structures.

Persistent Data Structures to avoid Mutability :

In order to use persistent data structures, we have to use some of the libraries like Mori, Immutablejs etc.

These two libraries are well known so we can proceed with any one as you will feel comfortable.

So, the next question comes in mind when we talk about Persistent DS is how they really work.

Let’s say we have the following array

The libraries which we have mentioned above comes with all help functions like map, reduce etc.

Let’s take another example, using the Persistent Data Structures.

So, this is all about functional programming in javascript, if you have any doubts or suggestions please comment it in the comment box.Thanks for reading this Blog.

Protractor (protractortest.org) is an end-to-end test framework specifically for AngularJS apps. It was built by a team in Google and released to open source. Protractor is built on top of WebDriverJS and includes important improvements tailored for AngularJS apps. Here are some of Protractor’s key benefits:

  • You don’t need to add waits or sleeps to your test. Protractor can communicate with your AngularJS app automatically and execute the next step in your test the moment the webpage finishes pending tasks, so you don’t have to worry about waiting for your test and webpage to sync.
  • It supports Angular-specific locator strategies (e.g., binding, model, repeater) as well as native WebDriver locator strategies (e.g., ID, CSS selector, XPath). This allows you to test Angular-specific elements without any setup effort on your part.
  • It is easy to set up page objects. Protractor does not execute WebDriver commands until an action is needed (e.g., get, sendKeys, click). This way you can set up page objects so tests can manipulate page elements without touching the HTML

Follow these simple steps, and in minutes, you will have you first Protractor test running:
 
1) Set up environment
Install the command line tools ‘protractor’ and ‘webdriver-manager’ using npm:
npm install -g protractor

Start up an instance of a selenium server:
webdriver-manager update & webdriver-manager start

This downloads the necessary binary, and starts a new webdriver session listening on http://localhost:4444.

2) Write your test

// It is a good idea to use page objects to modularize your testing logic
var angularHomepage = {
    nameInput: element(by.model('yourName')),
    greeting: element(by.binding('yourName')),
    get: function() {
        browser.get('index.html');
    },
    setName: function(name) {
        this.nameInput.sendKeys(name);
    }
};

// Here we are using the Jasmine test framework
// See http://jasmine.github.io/2.0/introduction.html for more details

describe('angularjs homepage', function() {
    it('should greet the named user', function() {
        angularHomepage.get();
        angularHomepage.setName('Julie');
        expect(angularHomepage.greeting.getText()).
        toEqual('Hello Julie!');
    });
});

3) Write a Protractor configuration file to specify the environment under which you want your test to run:

exports.config = {
    seleniumAddress: 'http://localhost:4444/wd/hub',
    specs: ['testFolder/*'],
    multiCapabilities: [{
        'browserName': 'chrome',
        // browser-specific tests
        specs: 'chromeTests/*'
    }, {
        'browserName': 'firefox',
        // run tests in parallel
        shardTestFiles: true
    }],
    baseUrl: 'http://www.angularjs.org',
};

4) Run the test:

Start the test with the command:

protractor conf.js

What is JavaScript?

JavaScript is a scripting language, created for making html-pages live. It turns the web into something more powerful than just interlinked html pages.

JavaScript has nothing in common with Java. It is a completely different language with a similar naming. JavaScript has the language specification called ECMAScript.

Programs in JavaScript are called scripts. They need no compilation, you just write a script, append it to HTML-page and it works.

Some people say JavaScript is like Python, some find it similar to Ruby or Self. The truth is that JavaScript is on its own, a really elegant but specific language.

What JavaScript can do?

  • Modify HTML page, write text in it, add or remove tags, change styles etc.
  • Execute code on events: mouse clicks and movements, keyboard input, etc.
  • Send requests to server and load data without reloading of the page. This technology is
    often called “AJAX”.
  • Get and set cookies, ask for data, output messages……And much, much more!

Modern JavaScript is a generic language. It is not browser-only. There are console programs and server Node.JS written in JavaScript. In this tutorial we’re talking about in-browser JavaScript only.

What JavaScript can’t do?

JavaScript is a generic language, fast and powerful.

But execution in browser context implies certain security limitations.

That’s because you surely don’t want a web-page script to execute with your privileges: read/write on hard disk, install software etc. The script must have strict security limitation not to harm your system, so you can open the page and feel safe. There are non-standard mechanisms of “signing” JavaScript, but not widely supported yet.

Most JavaScript abilities are limited by browser window.

  • JavaScript can’t read/write to hard disk, copy files and call other programs. It doesn’t have direct access to the OS. Newer browsers provide such abilities, but in a very limited and secure way.
  • JavaScript in one tab can’t affect other tabs/windows. There are exceptions, namely when two windows come from same domain.
  • A page with JavaScript can do network requests on it’s own domain without limitations. A request to another domain is also possible, but security measures apply.

Pre-coding tips

There are currently several main JavaScript/html engines available.

A regular web-site should look equally good in all of them.

Know your enemy: browser types

  • Firefox and other less known browsers which use an open-source engine called Gecko.
  • Safari/Chrome which both use an open-source rendering engine called Webkit, but different JavaScript implementations. Chrome uses Google V8 and Safari uses it’s own closed-source JavaScript engine. Because they both use Webkit, there’s a lot in common between them.
  • Opera uses it’s closed source engine called Presto.
  • Internet Explorer uses the closed-source engine called Trident. The engine is old and terrifying in IE6, IE7, but upgraded in IE8 and upgraded to much better standards compliance in IE9.

The terms Gecko, V8, Webkit are widely used in professional talks. Trident, Presto are less used.

Sometimes, the cross-browser development becomes complicated, so browsers are graded according to the level of support from A to C.

A. Latest Firefox, IE, Safari/Chrome
Supported ideally.

B. Opera, less recent major browsers
Supported well enough, but minor drawbacks in look and feel are possible.

C. Old major browsers
Only the core functionality of the site is supported.

D. Very old. Text browsers.
Not supported. If it works, it works. If it doesn’t, no one cares.
The grading above is an example from real life.

Choose the modern DOCTYPE

As you probably already know from HTML, there are two main rendering modes: Standards Mode and Quirks mode. Actually, there is a third mode called Almost Standards Mode, all of them described well in Wikipedia quirks mode page.

Browser chooses the mode according to DOCTYPE header of HTML.

For modern sites there is a good DOCTYPE:

This DOCTYPE make modern browsers render in Standards Mode and older ones in Almost Standards Mode (which is the maximum they can do).

Note, that the modern rendering mode is not just an HTML issue. There are JavaScript properties which also depend on the rendering mode, especially CSS-box and positioning-related.

Also, styles can be applied differently, for example Internet Explorer 7+ in standards-compliant mode (strict !DOCTYPE), can apply the :hover pseudo-class to any element (as it should), while in a non-strict mode it can only apply :hover to links.

Not using correct DOCTYPE will cost you time debugging. is ok.

Manuals and how to search in them

There are 2 main manuals on the net about JavaScript. One comes from Microsoft and called MSDN. They also call JavaScript a “JScript”.

Another one is documentation center of Mozilla Developer Network.

I use the following method of search. When I need to find “RegExp” in Mozilla documentation, I just type ”RegExp MDC” in google.

When I want to check MSDN, then “RegExp msdn”. Sometimes it helps to add additional “jscript” term: ”RegExp msdn jscript”.

MDN is usually good for general and firefox-specific information, while MSDN helps to deal with IE-specific features.

Incompatibilities

There are many cross-browser incompatibilities in frontend-programming. When you come across them, http://www.quirksmode.org/ may be a help.

It contains information about lots of incompatibilities. Also, there is a combo to search it. Try entering ”quirksmode onkeypress” in google for instance.

JavaScript is a general-purpose programming language. That’s why ECMAScript specification does not tell a word about browsers.

The browser stuff is described by a family of HTML5 standards.

The official W3.org DOM specifications are large, but extremely valuable. Use them as a reference.

The searching combo ”something site:w3.org” helps for DOM and Events-related questions.

The only problem with W3 is that it describes how it should be, not how it is.