JavaScript, some basic observations

So what are some basic changes from C?

In C we define veriables by type
int x; char ch; float my_num; and so on...
In JS, life is easier. var x; var ch; var my_num; and so on...
So what is the catch?
JS determines type by comparing with the value it has matched. For instance:
var x = 5; // makes x an integer
var ch = 'a'; // makes ch character type
var my_num = 3.14; // makes my_num float type

// Arrays are a bit different. They can be of mixed types
// Indexing is still 0 based, But note [] braces instead of {}
var arr = [1, "one", 2, 3, "five", 8, 13, 21, 34];

// Arrays are a type of objects in JS. An eg. of an object is:
var person = {firstName:"John", lastName:"Doe", age:46};

// Oh, and commenting is the same as in C
// Also, All lines end with semi-colons

As a magical bonus, there are many wonderful inbuilt functions that make life easier! For instance:
// given an array called cars
var len = cars.length; // saves length of array cars into var len
cars.sort(function(a,b){ return b-a;}); // sorts the array in descending order
var val_popped = cars.pop(); // you can even implement stacks and queues

To make things better, selection and iterative constructs are the same!
ie. your if - else , switch , for , while , etc... are the same!
There are also other for loops (for-in, for-of) that you can use.


HTML integration

At this point, the language should be easy to figure
But how do I integrate with an HTML file?

  1. Writing into an Alert Box
    < script >
    window.alert("My message");
    < /script >

    This results in A pop-up box with the message on it.

  2. Logging to console (Useful for debugging)
    < script >
    console.log("information to be logged");
    < /script >

    This results in log message being presented in console window.
    Can open console window in browser by [F12]

  3. Document write function
    < script >
    document.write("What is to be written");
    < /script >

    This is used to re-write complete page with new content.
    May be used for debugging or to write complete pages?

  4. Using innerHTML (FINALLY something really useful!)
    < p id="para">Hello< /p >
    ...
    < script >
    document.getElementById("para").innerHTML = "World";
    < /script >

    This code segment changes the content of < p > from "Hello" to "World".


Functions in JS

Let me explain this using button/link click action as an example:
< html >
< body >
< a href="" id="B1" onClick = "MYFUNC("Hi")"> Hello < /a >
...
< script >
function MYFUNC(new_text)
  {document.getElementById(B1).innerHTML = new_text;}
< /script>
< /body >
< /html >

This code segment invokes MY_FUNC when our button/link is clicked. It replaces the text "Hello" with "Hi" (or any other parameter passed).