Friday, 6 March 2015

BASIC Programming

Anybody can write a program. A background in mathematics or science is not required. Patience, practice, and an interest in the subject matter should suffice, along with the required software and hardware.
Understanding programs can appear daunting at first, but their reliance on logical operations allow for easy learning of commands which you will commonly see in many programs.
A program itself is merely a series of commands in the order in which they are to be executed. That is to say, that the first line is the beginning of the program!
All programs a user uses from day to day, including browsers (Internet Explorer, Firefox, etc.) and operating systems (Windows, *nix and MacOS) are separate sets of lines of code, which aim to fulfill tasks. the amount of code is dependent on how simple the task generally, and different types of code may be used for the advantages they give. BASIC is considered an excellent starting point for moving onto other languages, and can be useful for simple programs.

Programming Languages

Programming languages allow people to give instructions to a computer with commands that both the computer and the programmer can understand. Different programming languages use different commands and different rules for entering those commands; similar to the way people speak different words to each other with the same meaning. One person may say "hello", while another says "hola", which, although express the same thought, appear different.
Similarly other human languages, such as French and Spanish, are similar to each other, as computer programming languages can be also. Programming languages that are similar are usually referred to as related languages. Once a person learns a programming language, it is easier to then learn other programming languages especially those related to the first one, as many similarities in structure are shared between languages, especially those with a common ancestor.

The language taught here, BASIC, is easier to learn than others as its commands are similar to English and has a simple set of rules for entering them.

JavaScript

JavaScript is the most popular programming language in the world.
JavaScript is the programming language of the Web.
All modern HTML pages are using JavaScript.
JavaScript is easy to learn.

In HTML, JavaScript code must be inserted between <script> and </script> tags.

Example

<script>
       document.getElementById("demo").innerHTML = "My First JavaScript";
</script>

 JavaScript Programs

A computer program is a list of "instructions" to be "executed" by the computer.
In a programming language, these program instructions are called statements.
JavaScript is a programming language.
JavaScript statements are separated by semicolon.

Keywords or Reserved Words (like College, Car, Male, Company)

In JavaScript, some identifiers are reserved words and cannot be used as variables or function names.
JavaScript keywords are used to identify actions to be performed.
The var keyword tells the browser to create a new variable:
var x = 5 + 6;
var y = x * 10;

Identifiers (like Indira, Mercedes, Dinesh,  Aptara)

Identifiers can be short names (like x and y), or more descriptive names (age, sum, totalVolume).
The general rules for constructing names for variables (unique identifiers) are:
  • Names can contain letters, digits, underscores, and dollar signs.
  • Names must begin with a letter
  • Names can also begin with $ and _ (but we will not use it in this tutorial)
  • Names are case sensitive (y and Y are different variables)
  • Reserved words (like JavaScript keywords) cannot be used as names
Note
In HTML, JavaScript programs can be executed by the web browser.
JavaScript Statements
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.
JavaScript Values
The JavaScript syntax defines two types of values: Fixed values and variable values.
Fixed values are called literals. Variable values are called variables.
JavaScript Literals
The most important rules for writing fixed values are:
Numbers are written with or without decimals:
10.50

1001

 Strings are text, written within double or single quotes:
"John Doe"

'John Doe'

 Expressions can also represent fixed values:
5 + 6

5 * 10
JavaScript Variables
In a programming language, variables are used to store data values.
JavaScript uses the var keyword to define variables.
An equal sign is used to assign values to variables.
In this example, x is defined as a variable. Then, x is assigned (given) the value 6:
var x;

x = 6;

 
JavaScript Operators
JavaScript uses an assignment operator ( = ) to assign values to variables:
var x = 5;
var y = 6;

JavaScript uses arithmetic operators ( + - *  / ) to compute values:
(5 + 6) * 10

JavaScript Comments
Not all JavaScript statements are "executed".
Code after double slashes // or between /* and */ is treated as a comment.
Comments are ignored, and will not be executed:
var x = 5;   // I will be executed

// var x = 6;   I will NOT be executed

JavaScript is Case Sensitive
All JavaScript identifiers are case sensitive
The variables lastName and lastname, are two different variables.
lastName = "Doe";
lastname = "Peterson";

JavaScript does not interpret VAR or Var as the keyword var.
Note
It is common, in JavaScript, to use camelCase names.
You will often see names written like lastName (instead of lastname).

JavaScript Arithmetic Operators
Arithmetic operators are used to perform arithmetic between variables and/or values.
Operator
Description
+
Addition
-
Subtraction
*
Multiplication
/
Division
%
Modulus
++
Increment
--
Decrement
JavaScript Assignment Operators
Assignment operators are used to assign values to JavaScript variables.
Operator
Example
Same As
=
x = y
x = y
+=
x += y
x = x + y
-=
x -= y
x = x - y
*=
x *= y
x = x * y
/=
x /= y
x = x / y
%=
x %= y
x = x % y
The = assignment operator assigns a value to a variable.
Adding Strings and Numbers
Adding two numbers, will return the sum, but adding a number and a string will return a string:
Example
x = 5 + 5;
y = "5" + 5;
z= "Hello" + 5;
The result of x, y, and z will be:
10
55
Hello5

JavaScript Data Types
JavaScript variables can hold many data types: numbers, strings, arrays, objects and more:
var length = 16;                               // Number
var lastName = "Johnson";                      // String
var cars = ["Saab", "Volvo", "BMW"];           // Array
var x = {firstName:"John", lastName:"Doe"};    // Object
The Concept of Data Types
In programming, data types is an important concept.
To be able to operate on variables, it is important to know something about the type.
Without data types, a computer cannot safely solve this:
var x = 16 + "Volvo";
Does it make any sense to add "Volvo" to sixteen? Will produce a result? Will it produce an error?
JavaScript will treat the example above as:
JavaScript:
var x = "16" + "Volvo";
Note
If the second operand is a string, JavaScript will also treat the first operand as a string. 
Example:
var x = 16 + "Volvo";
JavaScript evaluates expressions from left to right. Different sequences can produce different results:
var x = 16 + 4 + "Volvo";

Result:
20Volvo

JavaScript:
var x = "Volvo" + 16 + 4;

Result:
Volvo164
In the first example, JavaScript treats 16 and 4 as numbers, until it reaches "Volvo".
In the second example, since the first operand is a string, all operands are treated as strings.
JavaScript Has Dynamic Types
JavaScript has dynamic types. This means that the same variable can be used as different types:
Example
var x;               // Now x is undefined
var x = 5;           // Now x is a Number
var x = "John";      // Now x is a String
JavaScript Strings
A string (or a text string) is a series of characters like "John Doe".
Strings are written with quotes. You can use single or double quotes:
Example
var carName = "Volvo XC60";   // Using double quotes
var carName = 'Volvo XC60';   // Using single quotes
You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
Example
var answer = "It's alright";             // Single quote inside double quotes
var answer = "He is called 'Johnny'";    // Single quotes inside double quotes
var answer = 'He is called "Johnny"';    // Double quotes inside single quotes

You will learn more about strings later in this tutorial.
JavaScript Numbers
JavaScript has only one type of numbers.
Numbers can be written with, or without decimals:
Example
var x1 = 34.00;     // Written with decimals
var x2 = 34;        // Written without decimals
Extra large or extra small numbers can be written with scientific (exponential) notation:
Example
var y = 123e5;      // 12300000
var z = 123e-5;     // 0.00123

You will learn more about numbers later in this tutorial.
JavaScript Booleans
Booleans can only have two values: true or false.
Example
var x = true;
var y = false;
Booleans are often used in conditional testing.
You will learn more about conditional testing later in this tutorial.
JavaScript Arrays
JavaScript arrays are written with square brackets.
Array items are separated by commas.
The following code declares (creates) an array called cars, containing three items (car names):
Example
var cars = ["Saab", "Volvo", "BMW"];

Array indexes are zero-based, which means the first item is [0], second is [1], and so on.
You will learn more about arrays later in this tutorial.
JavaScript Objects
JavaScript objects are written with curly braces.
Object properties are written as name:value pairs, separated by commas.
Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

The object (person) in the example above has 4 properties: firstName, lastName, age, and eyeColor.
You will learn more about objects later in this tutorial.
The typeof Operator (like calculator input check and validate)
You can use the JavaScript typeof operator to find the type of a JavaScript variable:
Example
typeof "John"                // Returns string
typeof 3.14                  // Returns number
typeof false                 // Returns boolean
typeof [1,2,3,4]             // Returns object
typeof {name:'John', age:34} // Returns object

 
Note
In JavaScript, an array is a special type of object. Therefore typeof [1,2,3,4] returns object. 
Undefined
In JavaScript, a variable without a value, has the value undefined. The typeof is also undefined.
Example
var person;                  // The value is undefined, the typeof is undefined

You will learn more about undefined later in this tutorial.
Empty Values
An empty value has nothing to do with undefined.
An empty string variable has both a value and a type.
Example
var car = "";                // The value is "", the typeof is string

JavaScript Functions
A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is executed when "something" invokes it (calls it).

Example

function myFunction(p1, p2) {
    return p1 * p2;              // The function returns the product of p1 and p2
}

JavaScript Function Syntax

A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
The parentheses may include parameter names separated by commas: (parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: {}
function functionName(parameter1, parameter2, parameter3) {
    code to be executed
}
Function parameters are the names listed in the function definition.
Function arguments are the real values received by the function when it is invoked.
Inside the function, the arguments are used as local variables.
Note
A Function is much the same as a Procedure or a Subroutine, in other programming languages.

Function Invocation

The code inside the function will execute when "something" invokes (calls) the function:
  • When an event occurs (when a user clicks a button)
  • When it is invoked (called) from JavaScript code
  • Automatically (self invoked)
You will learn a lot more about function invocation later in this tutorial.

Function Return

When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement.
Functions often compute a return value. The return value is "returned" back to the "caller":

Example

Calculate the product of two numbers, and return the result:
var x = myFunction(4, 3);        // Function is called, return value will end up in x

function myFunction(a, b) {
    return a * b;                // Function returns the product of a and b
}
The result in x will be:
12

Why Functions?

You can reuse code: Define the code once, and use it many times.
You can use the same code many times with different arguments, to produce different results.

What happens when you type a URL in browser?






Here details of what happens in the background when we type a URL in our browsers.
Step 1. URL is typed in the browser.

Step 2. If requested object is in browser cache and is fresh, move on to Step  8.

Step 3. DNS lookup to find the ip address of the server
when we want to connect to google.com, we actually want to reach out to a server where google web services are hosted. One such server is having an ip address of 74.125.236.65. Now, if you type "http://74.125.236.65" in your browser, this will take you to google home page itself. Which means, "http://google.com" and "http://74.125.236.65" are nothing but same stuff. But, it is not so. Google has multiple servers in multiple locations to cater to the huge volume of requests they receive per second. Thus we should let Google decide which server is best suited to our needs. Using "google.com" does the job for us. When we type "google.com", DNS(Domain Name System) services comes into play and resolves the URL to a proper ip address.

Following is a summary of steps happening while DNS service is at work:
·         Check browser cache: browsers maintain cache of DNS records for some fixed duration. So, this is the first place to resolve DNS queries.
·         Check OS cache: if browser doesn't contain the record in its cache, it makes a system call to underlying Operating System to fetch the record as OS also maintains a cache of recent DNS queries.
·          Router Cache: if above steps fail to get a DNS record, the search continues to your router which has its own cache.
·          ISP cache: if everything fails, the search moves on to your ISP. First, it tries in its cache, if not found - ISP's DNS recursive search comes into picture. DNS lookup is again a complex process which finds the appropriate ip address from a list of many options available for websites like Google. You can read more about this here.
Step 4. Browser initiates a TCP connection with the server.

Step 5. Browser sends a HTTP request to the server.
Browser sends a GET request to the server according to the specification of HTTP(Hyper Text Transfer Protocol) protocol.
        
GET http://google.com/ HTTP/1.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:29.0) Gecko/20100101 Firefox/29.0
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
Host: google.com
Cookie: datr=1265876274-[...]; locale=en_US; lsd=WW[...]; c_user=2101[...]
      
Here, browser passes some meta information in the form of headers to the server along with the URL - "http://google.com". User-Agent header specifies the browser properties, Accept-Encoding headers specify the type of responses it will accept. Connection header tells the server to keep open the TCP connection established here. The request also contains Cookies, which are meta information stored at the client end and contain previous browsing session information for the same website in the form of key-value pairs e.g. the login name of the user for Google.

A quick guide to HTTP specification can be found here.
Step 6. Server handles the incoming request
HTTP request made from browsers are handled by a special software running on server - commonly known as web servers e.g. Apache, IIS etc. Web server passes on the request to the proper request handler - a program written to handle web services e.g. PHP, ASP.NET, Ruby, Servlets etc.
      
For example URL- http://edusagar.com/index.php is handled by a program written in PHP file - index.php. As soon as GET request for index.php is received, Apache(our webserver at edusagar.com) prepares the environment to execute index.php file. Now, this php program will generate a response - in our case a HTML response. This response is then sent back to the browser according to HTTP guidelines.
Step 7. Browser receives the HTTP response
HTTP/1.1 200 OK
Cache-Control: private, no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Pragma: no-cache
Content-Encoding: gzip
Content-Type: text/html; charset=utf-8
Connection: Keep-Alive
Content-length: 1215
Date: Fri, 30 May 2014 08:10:15 GMT

.........<some blob> ................

HTTP response starts with the returned status code from the server. Following is a very brief summary of what a status code denotes:        
·                 1xx indicates an informational message only
·                 2xx indicates success of some kind
·                 3xx redirects the client to another URL
·                 4xx indicates an error on the client's part
·                 5xx indicates an error on the server's part
Server sets various other headers to help browser render the proper content. Content-Type tells the type of the content the browser has to show, Content-length tells the number of bytes of the response. Using the Content-Encoding header's value, browsers can decode the blob data present at the end of the response.
Step 8. Browsers displays the html content
Rendering of html content is also done in phases. The browser first renders the bare bone html structure, and then it sends multiple GET requests to fetch other hyper linked stuff e.g. If the html response contains an image in the form of img tags such as <img src="/assets/img/logo.png" />, browser will send a HTTP GET request to the server to fetch the image following the complete set of steps which we have seen till now. But this isn't that bad as it looks. Static files like images, javascript, css files are all cached by the browser so that in future it doesn't have to fetch them again.     
Step 9. Client interaction with server
Once a html page is loaded, there are several ways a user can interact with the server. For example, he call fill out a login form to sign in to the website. This also follows all the steps listed above, the only difference is that the HTTP request this time would be a POST instead of GET and along with that request, browser will send the form data to the server for processing (username and password in this case).
      
Once server authenticates the user, it will send the proper HTML content(may be user's profile) back to the browser and thus user will see that new webpage after his login request is processed.
Step 10. AJAX queries
Another form of client interaction with server is through AJAX(Asynchronous JavaScript And XML) requests. This is an asynchronous GET/POST request to which server can send a response back in a variety of ways - json, xml, html etc. AJAX requests doesn't hinder the current view of the webpage and work in the background. Because of this, one can dynamically modify the content of a webpage by calling an AJAX request and updating the web elements using Javascript.