JavaScript : Basics

Before going into manipulating html stuffs using javascript, lets see some of the elementary things in javascript. I would be using Ecilpse IDE for building. Usually a ‘static web project’ is ideal for this, as it already loads js lib so that development can be easy. However, I would be creating ‘dynamic web project’ and running in the server tomcat as later on we would be adding Ajax calls. For this post and may be couple after you can run directly the file on browser, no need for a server as we wont be doing any calls to backend. If creating dynamic webproject make sure to check JS lib so it would be easier to develop.

JS0-creatingproject

JS0-projectStrucure

All out html pages will be in ‘pages’ folder and js files will be in ‘js’ folder.

Javascript code written in ‘script’ element in html which was introduce in version 3. Usually js code is in head region of html, but it could be written anywhere. Creating a html ‘NewFile1.html’ inside pages folder:


<!DOCTYPE html>
<html>
<head>
<title>NewFile1 Html</title>

<script type="text/javascript">
alert("Hi, There!!");
</script>

</head>
<body>

<script type="text/javascript">
alert("Hi, There Again!!");
</script>

</body>
</html>

Running this will produce 2 popups. As a good coding practice, many projects started putting all js code in a seperate file and then linking it to the html. New File1.html:


<!DOCTYPE html>
<html>
<head>
<title>NewFile1 Html</title>

<script type="text/javascript" src="../js/new_file1.js"></script>

</head>
<body>

</body>
</html>

Creating new_file1.js inside js folder:


alert("Hi from new_file1.js");

Running html will again produce an alert. Now when the browser loads an html page, it starts from the top and load one by one. Since js files are define inside head, the browser stops loading the html after it and first loads all the js code and then continue with html loading. Now the end user will only see the page after all the loading of js code is done. So because of this , we started to place our script tag at the end, just before the end ‘body’ tag. This allows the browser to display html first and then load the js files. So if its not important to run js code first, its advisable to keep the script tag at the end.


<!DOCTYPE html>
<html>
<head>
<title>NewFile1 Html</title>
</head>
<body>

<script type="text/javascript" src="../js/new_file1.js"></script>
</body>
</html>

Data Types

JavaScript has dynamic types. This means that the same variable can be used as different types. 

  • Strings are written with quotes. You can use single or double quotes.
  • Numbers can be written with, or without decimals.
  • Booleans can only have two values: true or false.
  • Arrays are written with square brackets. Array items are separated by commas.
    var personss = [“John”, “Jake”, “Leo”];
  • Objects are written with curly braces. Object properties are written as name:value pairs, separated by commas.
    var person = {firstName:”John”, lastName:”Doe”, age:50};
  • Undefined – variable with no value
    var person;
  • Null – Variables can be emptied by setting the value to null
    person = null;

typeof() function  can be used to check what type a variable is.
typeof(“john”); // Returns “string”
typeof(3.14); // Returns “number”

When a variable is declared with the keyword “new”, the variable is declared as an object. (var name = new String;)

Functions

Functions are block of code designed to perform a particular task. We can create functions on the fly, we can assign functions to a variable and we can pass them to other fuctions, so basically functions are a type of data in javascript that allows us to do a lot of thing with them. Typical declaration:


function getPerson(fname,lname){
var fullName="Hello "+fname+" "+lname;
return fullName;
}
var x=getPerson("John","Doe");
alert(x);

This will alert the name. Other way to declare as assignment to a variable:


var getPerson=function (fname,lname){
var fullName="Hello "+fname+" "+lname;
return fullName;
};
var x=getPerson("John","Doe");
alert(x);

Notice the semicolon at the end of the function block as we are assigning it to a variable. If we add ‘()’ at the end of the fuction before ‘;’ then we are executing the fuction then and there, but that will break our present code. Modifying:


var getPerson = (function() {
return function(fname, lname) {
var fullName = "Hello " + fname + " " + lname;
return fullName;
};
}());
var x = getPerson("John", "Doe");
alert(x);

Here we are first defining a function that takes no parameters and executes right there (as we have a ‘()’ at the end) which returns the function which takes fname and lname as parameters. This type of pattern although unnecessary in this case but useful when we are dealing with events.

A variable declared (using var) within a JavaScript function becomes LOCAL to the function. The variable gets a local scope: It can only be accessed from within that function. A variable declared outside a function, becomes GLOBAL. The variable gets a global scope: All scripts and functions on the web page can access it. Local variables are deleted when the function is completed. Global variables are deleted when you close the page.

If you assign a value to a variable that has not yet been declared, the variable will automatically be declared as  GLOBALvariable.

This statement:

person = “John”;

will declare the variable carName as a global variable , even if it is executed inside a function.

Comparison operators are used in logical statements to determine equality or difference between variables or values. 

Given that x=5, the table below explains the comparison operators:

 

Operator Description Comparing Returns
== equal to x == “5” true
x == 5 true
=== exactly equal to (equal value and equal type) x === “5” false
x === 5 true
!=  not equal x != 8 true
!==  not equal (different value or different type) x !== “5” true
x !== 5 false

Rest >,<,>=,<=,||,&&,! are use the same way.
It also contains a conditional operator that assigns a value to a variable based on some condition.
variablename=(condition)?value1:value2

For conditional statements we have if, else, else if, switch.

avaScript supports different kinds of loops:

  • for – loops through a block of code a number of times
  • for/in – loops through the properties of an object
    var person = {fname:"John", lname:"Doe", age:25};
    
    var text = "";
    for (var x in person) {
    text += person[x];
    }
    alert(text)//will return JohnDoe25
    
    
  • while – loops through a block of code while a specified condition is true
  • do/while – also loops through a block of code while a specified condition is true

break, continue, labels are used same way like in other langs.

It is advisable not to use string concatenation everytime, better way will be to use arrays join method. Lets us see with an example:


var date = new Date();
var displayMessage = [
"Hello",
prompt("Please Enter your Name", "Enter Name here.."),
"Today is ",
date ];
alert(displayMessage.join(""));

Running this will prot user to enter name which will return the string the user enters. join(“”) will concenate all things with empty space. If we dont use any delimiter, it will take ‘,’ as default.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: