Thursday, 12 March 2015

JS writing to a page

There are a number of inbuilt JavaScript functions for this. alert() and document.write() are two of the most widely used JS functions for outputting JS texts from a webpage

alert( );

The alert function displays a dialogue box with the parameters of the function as content.
alert("How are you"); //This displays "How are you" in a dialogue box on the screen. Ok, let us write a proper JS code in its proper HTML tag.
<html>
<head>
           <script type="text/javascript" language="javascript">
           alert("How are you");
           </script>
</head>
<body>

</body>
</html>

The code above displays the image below;



Now, this is a dialogue box with an attitude. It basically freezes the webpage until you click on the OK button. All data-types can be put on a dialogue box basically. 
var number1 = 34;
var number2 = 22;
alert(2);  <- This prints a numeric value 2 on a dialogue box and displays it.
alert(number1 + number2); <- This prints 56 on a dialogue box and displays it,

document.write( );

This function takes a lighter approach to displaying user input. Unlike alert( ), it does not print it's parameter on a dialogue box. Rather, it displays it directly on a webpage.
<html>
<head>
           <script type="text/javascript" language="javascript">
           document.write("How are you");
           </script>
</head>
<body>

</body>
</html>

The code above displays the image below;



There are more methods basically that writes either to a webpage or to form elements such as textboxes. Methods such as .innerHTML and .value (Note the dot in before the words). These methods will be discussed in future blogposts.

Hope this helps someone out there.

Feel free to drop comments, suggestions and criticisms in the comment section below.

Joseph Kayode Agbede

Type conversion


This is the changing from a data-type to another. For example, integer to float, float to string, string to integer and so forth. This is also known as CASTING. The following in-built JS functions are used for conversion. 

parseInt()
parseFloat()
String()
Number()

 and a .toString() method.

Consider the following statements,

var count1 = "5";
var count2 = 6;

count1 + count2 //would result in 56

This is so because both variables are of different data-types. count1 is of string type and count2 is of integer type. These two data-types cannot be have an arithmetic computation between them. JavaScript will result to concatenate these two values.

To have a proper calculation performed between both variables, the variable with string type must be cast into integer type.


parseInt() / Number() function can be used here to convert string to integer. It is used thus,

Number(count1) + count2 //This will result in an 11 
parseInt(count1) + count2 //This will result in an 11.

String() function is used to convert values to string type. For example,

var num1 = 4;
var num2 = String(num1);

Num2 variable also has the value of 4 only that it is stringed. An alert(num2); will output "4" (Four with the quotes)

parseFloat()
This JS function is used to convert a numeric stringed value to a floating point number. Floating point numbers are numbers with decimal places e.g 34.003.

var value1 = "3423.34";
var value2 = parseFloat(value1); //This passes a true floating point value 3423.34 to value2 variable.

parseFloat("23.00"); //This outputs integer value 23.
parseFloat("23.01");//This outputs floatnumber 23.01.
parseFloat("How"); // Outputs NaN which means not a number. How is not a number.

Comments are welcome to the comment section of this blog.

Joseph Kayode Agbede
MCITP, RHCE and ITIL certified 

Wednesday, 11 March 2015

JavaScript Operators

JavaScript operators are used to compare, count, assign or to calculate. They are grouped into these classes;

1. Assignment operators
2. Comparison operators
3. Arithmetic operators
4. Counting operators

JS Assignment operators

Assignment operators are used to pass (or give) values to a variable. Look at the following for example
var who = "emmanuel";
The symbol "=" is the assignment operator in the example above. It passed a string value "emmanuel" to the variable name "who". The equals sign is the most used operator in almost all high level languages. There are more operators though.

+= 
An example of the above operator usage is 
                                                     C +=2;
What this basically means is that variable C be incremented by 2. The JavaScript statement above can be rewritten as var C = C + 2; which means that the new value of C should be the old value of C plus 2.

-=
The same principle applies for the operator above.
C -=2;
Means variable C be decremented by 2 everytime the statement is encountered. It can also be re-written as: C = C - 2.

*= and /= follow the exact same principle where asterick (*) is for multiplication and front-facing slash(/) is for division.

JS Comparison operators

Comparison operators are used for evaluation and comparison purposes. The following operators are used for comparison.

==, <=, >=, !=
== -> Means is it equal to?
<= -> is this less than or equal to?
>= -> is this greater than or equal to?
!= -> is this not equal to?
=== -> explicitly equal to?

var number1 = 5;
var number2 = 8;
var number3 = "8"; //Note that number3 here is holding a string value 8.

Comparison operators are answer seeking. Their output begs either a true or false answer. Using the JS variables declared above, consider the following statements below.

1
number1 >= number2 
(5 is greater than or equal to 8 ?)

The statement above reports a false because the integer value 5 is not greater or equal to 8.

2
number1 != number2 
(5 is not equal to 8 ?)
The above statement resolves to true since the integer number 5 is not the same as 8

3
number1 ==  number2 
(5 is equal to 8?)
The statement above compares the numeric values 5 and 8 and outputs false since they are not equal.

4
number2 == number3 
(8 is equal to "8"?)
Statement above compares the integer value 8 in number2 to the string value 8 in number3 and returns a true even though the datatypes are different.

5
number2 === number3 
(8 is both value-wise and data-type-wise equal to "8"?)
The statement above resolves to a false. Even though both variables contain the same value. But they are of different types.

JS Arithmetic operators

Arithmetic operators are used to perform calculations such as addition, subtraction, multiplication, division and modulus on numeric or floating point values. These operators are represented by the basic mathematical symbols (+, -, *, /, %). Yes, an asterisk is for multiplication not X - ecks.

var number1 = 5;

var number2 = 8;
var number3 = "8"; //Note that number3 here is holding a string value 8.

number1 * number2;  //outputs 40.
number2 % number5;  //outputs 3 (modulus is the reminder after division)

I believe you get the idea.

number1 + number3;
(5 + "8")
58 is output because the value of number3 is not a number. It is a string. JavaScript will therefore proceed to do what is called a concatenation of the two values which is simply the joining of the two values. More on concatenation in the near future.

JS Counting operators

Counting operators are for counting basically. And it does this by either incrementing or decrementing by one upon every encounter. (++, -- )

var number1 = 5;

var number2 = 8;

var increOne = ++number1; //increment number1 by one before assigning the value of number1 to increOne.

var increTwo = number2--; //Means, assign the value of number2 to increTwo before decrementing number2 by one

Now, when the counting operator is placed before a variable it means, the variable must first be incremented or decremented(depending on the symbol used) by one before its value is used.

When the counting operator is placed after a variable, it means the variable's value should be used before it is either incremented or decremented (depending on the symbol used)

alert(number1++); 
// This displays 5 in a dialogue box

alert(number1);
// This displays 6 in a dialogue box now, because its value has been incremented by one in the earlier statement. 


Feel free to drop your observation, a comment or a question in the comment section below.

Joseph Kayode Agbede

JS Data-Types

A data-type, simply put is a type of data. Consider the following values; "4", "6.3", "James".

4 is an Integer type as it is a whole number.

6.3 is a Floats type as it is a values with a decimal point.

James is a String type as it is composed of alphabets. Strings are alphabets, alphanumerics and symbols. Example of this is KAYODE, CSC101 etc.

Arithmetic computations can be performed only on integer values or floating point values.  e.g 3 + 5 or 4.634 - 2.423. Strings on the other hand cannot have calculations performed on it. We + Are does not resolve to a mathematical output. At best, strings can merely do what is called concatenation - the joining together of values.

4, 7, 723, 9239  <- Integer values.
9.523, 23.582, 412.9349 <- Floating point values
Kayode, Emmanuel, Townhall, Thesis, Gd24 <- String

There are actually more JS data-types. We have Arrays and Objects.

Array variables are capable of holding more than one value. Consider the example below.

var subjects = [34,"Computer Science",15.23,"Physics","History"];

Variable subjects in the example above holds 5 values. These values can actually be of different data-types. Only Arrays and Objects are capable of this.

Object variables also hold more than a single value. They hold properties and the corresponding values of the properties.

var objHuman = {name:"Kayode", age:25, Address:"Bacita", Phone:"07055518205"};

The variable objHuman is of object type And as shown above, the properties defined for the objHuman are the name, age, Address and phone. Each of the properties have their corresponding values attached to them.

A JS variable can be initialized with any of the data-type mentioned above.

Joseph Kayode Agbede

JavaScript Variables

JS Variables

Variables are like containers that hold values that can change. "Break" the word variable into two meaningful words and you have vary-able.

A variable holds value that can be used either in an arithmetic computation or in concatenation with other data-types at a later time.
var name = "James";

Name = "Kayode";

JavaScript variable definition rule does not insist on defining the type of values that can be passed to the variable when the variable is created. It is regarded a weakly typed language for this reason. A single JavaScript variable can hold a string, float, double or integer value.

The keyword var in the variable declaration above is not mandatory. JS variables can be defined with or without it. It is advised though to have it included in your variable declaration as some JS app developers have complained of inconsistencies in their application as a result of its exclusion.

Java on the other hand is a strongly typed language. This means that upon variable declaration, the specific data-type that the variable is allowed to store is defined. Take a look at the example below.



String value;
int count;

The variable name value is defined in the example above to hold only String values. Passing integer, float, or double to this variable will trigger an error. "count" in the variable declaration above stores only integer values. any attempt to store a value of a data-type other than integer will produce an error.

Local VS Global JS variable declaration

<script type="text/javascript" language="javascript">
var website = "www.dissertation.com.ng";

function whatis(){
var website2;
}

function almagamate(){
document.write(website);
//outputs www.dissertation.com.ng
document.write(website2); //This prints nothing to the screen as variable website2 is not within it's scope.
}

</script>

The script above clearly shows the difference between a local or procedural variable and a global variable. website is a global variable which can be called from anywhere in the script.

website2  on the other hand is a local variable. Local in the sense that it is available for use only within the function block whatis().


Initializing JS variables

Initialization is the passing of initial values to a variable. JS variables do not have to be initialized upon variable declaration. They can be created and stored either as procedural variables or global variables.


var website = "www.dissertation.com.ng"; 

The variable "website" in the example directly above is initialized with the value "www.dissertation.com.ng" upon declaration. But you really do not have to initialize a variable upon definition. I can also create the variable in the fashion below.


var website;

The above is a perfectly defined JS variable as well. Only that this variable does not have an initial value. We will look at scenerios where you do not want to initialize your variable upon declaration in future posts.

My next blog will be on data-types as it goes hand in hand with variables.

Enjoy!
Joseph Kayode Agbede

Tuesday, 10 March 2015

Introduction to JavaScript

For newbies into programming and oldies in the game, JavaScript is a web client-sided programming language used for developing applications that run directly on a web-browser and functions independently of the web-server.


All major web-browsers come pre-installed with Javascript interpreter so there is not much you really need to do get JavaScript codes up and running on your website. 

NOW! a major information to note here.. JavaScript is not Java.  They share the same first four characters but they are different languages. Java predates JavaScript. Java became really popular in the 1990's as a computer programming language. Developers of JavaScript really needed a name to push the language, thus JavaScript.


JavaScript is considered an Object Oriented Programming language to a degree. The concepts of inheritance, polymorphism and encapsulation are not fully in use in the language. It does make use of objects though. This we will explore in future write-ups.


JavaScript, like all languages of the world have rules of engagement. Means, to effectively communicate your needs to the web-browser, these rules must be adhered to to the dot. Some of these include.

1. JS sentences terminate with a semi-colon - Just like a sentence in English ends with a full-stop(.), JavaScript terminates its sentence with a semi-colon (;). Take a look at the JS statement below,
alert("Hi there");

Notice the termination symbol at the end of the sentence above. If your statement is not terminated properly, JS may just choose to not work. I battled with this very rule years back as a newbie into programming. Hundreds of lines of code would just not work for failing to put in a little silly semi-colon (;) in its appropriate place. The symbol can make or mar your script basically. You want to be really careful here.

2. JS is case-sensitive - You really want to watch this one too. You will find yourself committing the same case-sensitivity mistake over and over and yes, they can rubbish your entire script.

alert() and Alert() are different.
window.onload() and window.onLoad() are also very different

The JS function alert() begins with a lowercase letter "a". Replacing the small case "a" with an uppercase letter "A"; i.e Alert(); you would have created a bug in your script and your javascript code will not work.

There are loads of functions, classes and methods that come in-built with your web-browser. They all require that you call and use them exactly as they were created.

3. JS statements are written inside HTML script opening and closing tags.

<script>
//Javascript statements here
</script>

JavaScript statements cannot be defined outside of HTML script tags. That is the only area in which your JS statements can be created for it to be processed by the JS interpreter. 

These are three major rules that have to be followed to work with JavaScript.

Joseph Kayode Agbede

JS; Random Question generator.

My approach to solving this problem may be different from the approach you will adopt to solving the same problem. But in all, it generates and prints random questions at every web-browser refresh from a list of pre-registered questions.


For this solution, I will be working with a data-type called array. The reason for this should be quite obvious. Array variables hold loads of values.. and our values? You got it, will be the questions.

Let us start therefore by defining an array variable to hold 7 questions.


var questions = new Array(7);

There, we just created an array variable "questions" with a length of 7. We now need to put in the questions into the array.

questions[0] = "What is your name?"
questions[1] = "How old are you?"
questions[2] = "Your primary school name is?"
questions[3] = "Your mother's maiden name"
questions[4] = "Your first dog is of what breed?"
questions[5] = "You have just how many toes?"
questions[6] = "Your favourite meal will be?"

You get the drift yes? Array index values begin at zero. Take this as a rule of thumb; 


Maximum index value of an array = length of the array - 1

So an array of length 20 has its maximum index value at 19 since index count begins from zero i.e 0,1,2,3,...19.

Great! Now to display our questions stored in this array at random, we invoke a Math.random() function.

The random() method of a Math class is really a weak method. It merely outputs floating point values between zero and one. Values such as 0.2342533. 


We actually want the javascript interpreter to deduce integer values from 0 - 6 which should serve as our index value for our questions array when the time is right. 

//Generating the numbers from 0 - 6 randomly.
var randNumb = Math.floor(Math.random() * 7 );

Math.floor - Rounds down the floating point value in its brackets to an integer.
Math.random() * 7 - generates a random floating point value between 0 and 1.

document.write(questions[randNumb]);

The JS statement above print out random questions from 0 - 6. 

//The script in its full form 

document.write("Welcome to my random question generator script");
var questions = new Array(7);
questions[0] = "What is your name?"
questions[1] = "How old are you?"
questions[2] = "Your primary school name is?"
questions[3] = "Your mother's maiden name"
questions[4] = "Your first dog is of what breed?"
questions[5] = "You have just how many toes?"
questions[6] = "Your favourite meal will be?"
var randNumb = Math.floor(Math.random() * 7 );
document.write(questions[randNumb]);

//End of script

Enjoy.
Joseph Kayode Agbede