Saturday, December 23, 2017

JavaScript - If, Else,Else if , Switch Conditions - Day 21

Conditions are used to do particular conditions several times.

Following are some conditions used in JavaScript

if condition will execute a block of code.., if is used when statement is whether true or false.
else condition used when a block of statement is false
else if condition used to check more & more statements whether they are true
switch to specify many alternative blocks of code to be executed

If condition

if (condition) {
    block of code to be executed if the condition is true}

if should be in lower case... if is in uppercase then JavaScript will show error.

<p id="demo"></p>

<script>
if (5 == 5) {
    document.getElementById("demo").innerHTML = "True";
}
</script>

Output : True

Else Condition

<p id="demo"></p>

<script>
if (5 == 7) {
    document.getElementById("demo").innerHTML = "True";
}else {
    document.getElementById("demo").innerHTML = "False";
}
</script>

Output: False

Else if Statement

if (condition1) {
   statement
} else if (condition2) {
   statement
} else {
   statement
}

Switch Statement

switch(expression) {
    case n:
        code
        break;
    case n:
        code
        break;
    default:
     code
}

Break Keyword : When execution reached Break keyword the program will run out of Switch statement. If we don't use Break all codes will be read by device. 

Default Keyword : The default keyword specifies the code to run if there is no case match

JavaScript Arrays - Day 20

Arrays are one of the Type of Object. Its used to store many variable in a single variable using Index values. In objects we use name:value property to store and when call the object the same procedure.

But Array is little different..

We call Arrays using Index. The first index is 0 (Zero-based Index).

To Create an Array :---

var array_name = [item1, item2, ...];

<p id="demo"></p>
<script>

var cars = ["Saab", "Volvo", "BMW"];

document.getElementById("demo").innerHTML = cars;

</script>

Output: Saab,Volvo,BMW


Another way of creating Array is
var Array_name = new Array( );

E.g: 
<p id="demo"></p>

<script>
var cars = new Array("Maruthi", "Fiat", "Nissan");
document.getElementById("demo").innerHTML = cars;
</script>

Output: Maruthi, Fiat, Nissan

Accessing Array
1. Using indexing Method

<p id="car_info"></p>

<script>

var cars = ["Maruthi", "Fiat", "Lamborgini"];

document.getElementById("car_info").innerHTML = cars[0];

</script>

Output: Maruthi

2.  Calling the Name inside curly braces

<p id="first"></p>

<script>
var person = {firstName:"Parathan", lastName:"Thiyaa", age:19};
document.getElementById("first").innerHTML = person["firstName"];
</script>

Output:  Parathan

Length of Array : This will return the number of values in the Array.
<p id="demo"></p>

<script>

var fruits = ["Banana", "Orange", "Apple", "Mango"];

document.getElementById("demo").innerHTML = fruits.length;

</script>


Output:4

typeof

This will return the Data Type of the variable..

E:g-
<p id="type"></p>

<script>
var person = ["Parathan", "Saravanan", "Varshanan"];
document.getElementById("type").innerHTML = typeof person;
</script>

Output: object

Array.isArray() : This method will check if that variable is an array or not.


<p id="test"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("test").innerHTML = Array.isArray(fruits);
</script>

Output: true

Another way of instanceof array is used to test the array

<p id="demo"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits instanceof Array;
</script>

Output: true

Monday, December 18, 2017

Math Function and Numbers in JavaScript - Day 19

Math Function is used to do mathematical works in JavaScript. Lets know one by one.

  • Math.PI  == Will output the value of PI
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = Math.PI;
</script>

Output:  3.141592653589793

  • Math.round(num) 
Replace num with any decimal numbers. You will get the answer as a whole number which is nearly to the decimal number.

  • Math.pow(x,y) will out put the x to the power of y.
Eg: Math.pow(3,2)
Output: 8

  • Math.sqrt()
The above will give the square root of a given number.
E.g:   Math.sqrt(4)
Output: 2

  • Math.random() will give a random number
  • Math.floor will output the maximum whole number below that decimal number.
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = Math.floor(Math.random()*50);
</script>


The above function will return Random numbers between 50. The output will change time to change when you run the code.

*50 defines the range of Random numbers to be selected.


Math.min() and Math.max()

Math.min() and Math.max() can be used to find the lowest or highest value in a list of arguments.

Output the Date & Time using JS

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = Date();
</script>


If you want to Output a Particular Date & Time..

<p id="demo"></p>

<script>
var d = new Date("October 13, 2014 11:13:00");
document.getElementById("demo").innerHTML = d;
</script>

Output:    Mon Oct 13 2014 11:13:00 GMT+0530

Numbers

<p id="demo"></p>

<script>
var x = 2456e6;
var y = 2456-5;

document.getElementById("demo").innerHTML = x + "<br>" + y;
</script>

Output:
2456000000
0.02456

e means Exponential & e5 means 10 to the powers of 5. e-5 = 10 to the power of -5.

Adding Numbers

<p id="demo"></p>

<script>
var x = 30;
var y = 20;
var z = x + y;
document.getElementById("demo").innerHTML = z;
</script>

Output : 50

Adding Strings & Numbers

<p id="demo"></p>

<script>
var x = "540";
var y = "560";
var z = x + y;
document.getElementById("demo").innerHTML = z;
</script>

Output: 540560

Here inside the double quotation JS will take as String, therefore it will print as it is.

NaN - Not a Number

NaN is a JavaScript reserved word indicating that a number is not a legal number.

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 100 / "Orange";
</script>

Output: NaN

JavaScript - Objects - Day 18

Variables are used to assign single data values. Objects are also Variables.But object can contain many values.

<html>
<body>

<p id="para"></p>

<script>
var Parathan = {age:"19", Town:"Jaffna", like:"Movies"};
document.getElementById("demo").innerHTML = Parathan.Town;
</script>

</body>
</html>


Output : Jaffna

To get output from Objects we use name, value pairs. name:values

JavaScript objects are containers for named values called properties or methods.
We can use Two types to access Objects.
  • objectName.propertyName
  • objectName["propertyName"]   

Object Constructors

We are also able to create objects using constructor functions.

A constructor function is given a capitalized name to make it clear that it is a constructor.

Here's an example of a constructor function:

var Car = function() {
this.wheels = 4;
this.engines = 1;
this.seats = 5;
};

In a constructor the this variable refers to the new object being created by the constructor. So when we write,

this.wheels = 4;

inside of the constructor we are giving the new object it creates a property called wheels with a value of 4.

You can think of a constructor as a description for the object it will create.

Tuesday, December 12, 2017

JavaScript Functions - Day 18

Function is a line of code which is write for one time & can be reused again & again. So, these functions eliminates writing a specific code again & again in a program.
How to Write a Function...??/
We have to start with "function" keyword and then we have to name the function. Then a parameter which contain parameters or null should be written.. after that curly braces should be wriiten..

<script>
      function functionname (  parameter-list  )
      {
         statements
      }
</script>

Calling Function
So, now you have write the Function and then you have to call the function anywhere in the program to run.
Simply, you have to type the name of the function with parenthesis ()

<html>
   <head>
      <script>
         function sayHello()
         {
            document.write ("Hello there!");
         }
      </script>
   </head>
   <body>
      <p>Click the following button to call the function</p>
      <form>
         <input type="button" onclick="sayHello()" value="Say Hello">
      </form>
   </body>
</html>

Function With Parameters

Still we haven't put any parameters inside the function.So, now we have to practice with parameters
There is a way to insert parameters; when calling function inside parenthesis you can put the argument.

<html>
   <head>
      <script>
         function sayHello(name, age)
         {
            document.write (name + " is " + age + " years old.");
         }
      </script>
   </head>
   <body>
      <p>Click the following button to call the function</p>
      <form>
         <input type="button" onclick="sayHello('Parathan', 19)" value="Say Hello">
      </form>
   </body>
</html>
Click the following button to call the function


Return Statement inside a Function

If you want to get a statement from function you have to code this at the bottom of the function where it ends.
For example, you can pass two numbers in a function and then you can expect the function to return their multiplication in your calling program.

<html> 
<head> 
<script>
 function firstFunction(first, last) {
 var full; full = first + last; 
return full; 
} 
function lastFunction() { 
var result; 
result = firstFunction('Parathan', 'Thiyagalingam'); 
document.write (result ); 
}
 </script> 
</head> 
<body> 
<p>Click the following button to call the function</p> <form> 
<input type="button" onclick="lastFunction()" value="Call Function"> </form>
</body> 
</html>

Click the following button to call the function

JavaScript Syntax [ Identifiers, Variables, Comments ] - Day 17

As we already learned in last post... JavaScript can be inserted to a HTML page in both head & body tags. The following is a sample code of  "How JS works..??"

<html>
   <body>
      <script>
            document.write("Hello World!")  
      </script>
   </body>
</html>

Output: Hello World!

JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs. You can write with white space, newline & tabs for your readability.

End of Statement =>> Semicolon Used
If a single statement is finished it will be defined by a semi colons in most of the Programming Languages. But JS allows your code If you won't add a semi colon. Anyway writing with Semi colon is best idea. (It is a good programming practice to use semicolons.)

JavaScript is a Case Sensitive language as most of the Programming Languages.
This means that the language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters.

So, name , Name are different according to JavaScript...

Comments in JavaScript

For single line comment we use :   //
For multi line comment  we use :   /*  line goes here /*

JavaScript Identifiers

All JavaScript variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

The general rules for constructing names for variables  are:
  • Names can contain letters, digits, underscores, and dollar signs.
  • Names must begin with a letter
  • Names can also begin with $ and _
  • Names are case sensitive (y and Y are different variables)
  • Reserved words (JavaScript keywords) cannot be used as names
Variable 

When declaring a variable in JavaScript... 
var Syntax is used

Now, In ECMA 6 we can use const & let keyword also..
const means constants and let will change its value if you change the value...

Variable Scope in JS

Global Variable : Global Variable can be defined anywhere in your JavaScript code.

Local Variable : Local Variables can be visible only within a function where it is defined. Function parameters are always local to that function.

Have a look at this code

<html>
   <body>
      <script >

            var myVar = "global";                // Declare a global variable
            function parathan( ) {
               var myVar = "local";              // Declare a local variable
               document.write(myVar);
            }
         
      </script>
   </body>
</html>

Output : local

as document.write() is printed inside a function & that function contains a myVar variable... So, the output will display "local" only.

If you code document.write() outside the function then the output is "global"

The lifetime of a JavaScript variable starts when it is declared.

Local variables are deleted when the function is completed.

In a web browser, global variables are deleted when you close the browser window (or tab), but remains available to new pages loaded into the same window.

Intro to JavaScript - Day 16

JavaScript is one of the main 3 languages that a developer should know.
  1. HTML
  2. CSS
  3. JavaScript
JavaScript is like a programming language in Web development. We can make movements & graphical (Dynamic Pages) movement in a webpage using JS. 
JS is a lightweight, more easy to learn & user friendly.

JavaScript was first known as LiveScript / ECMA Script, but Netscape changed its name to JavaScript. 

Following are some characterestics of JS

  • JavaScript is a lightweight, interpreted programming language.
  • Designed for creating network-centric applications.
  • Complementary to and integrated with Java.
  • Complementary to and integrated with HTML.
  • Open and cross-platform
We use JS while check whether the user entered a valid e-mail address in a form.
If and only if the user entered valid entries only JS starts to execute the code & submit the values to the Web Server.

Advantages of JavaScript
  • Richer interfaces − You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors.
  • Less server interaction − We can validate the entries of users before they submitted to the Servers. This will reduce the traffic to the web server. 
  • Immediate feedback to the visitors − If users forget to submit any required info JS will tell them to submit.
  • Increased interactivity − When user take the mouse cursor near JS coded gadget it will react immediately.
Type of Inserting JavaScript in HTML

You can add JavaScript in 
  1. <body> Tag
  2. <head> Tag
  3. In both body & head Tag

Inserting External JavaScript

You can insert JavaScript externally as you insert CSS

<script src="myScript.js"></script>

You have to replace the myScript.js with your external JavaScript path.


Different types of JavaScript Display Possibilities

into an HTML element, using .innerHTML
into the HTML output using document.write()
into an alert box, using window.alert()
into the browser console, using console.log()

JavaScript accepts both double and single quotes:

Here, "demo" is name of ID which will be call in a HTML page...
Don't worry about it..

document.getElementById("demo").style.fontColor = "Brown";

document.getElementById('demo').style.fontColor = 'Brown';

JavaScript takes both " " and ' ' as same... So, no  problem when typing....

Advantages of Using External JavaScript 
  • Easy to read the code 
  • Cached Script codes will be stored in browser..So loading would be faster
  • Seperates HTML and script code
Nowadays JavaScript Version 5 & Version 6 are used. [ ECMA 5 & ECMA 6]