#1
  1. Moderator From Beyond
    ASP Mastermind (5000+ posts)

    Join Date
    Sep 2004
    Location
    Israel
    Posts
    31,135
    Rep Power
    2922

    There Is No Magic: JavaScript Tutorial


    Finally I've found the time to do something I planned to do
    for long long time: writing tutorial for JavaScript, based on
    my personal experience with JavaScript.

    Keep in mind that my tutorial is not official and there
    might be better ways to do some of the things. If you happen
    to notice such thing then please say something so that I can
    both learn and improve this tutorial.

    There will be several parts, I will post each part as reply in this
    thread and keep updated index here in the first post.

    Here we go then!

    Introduction to JavaScript

    What? Why? How?

    What is it?
    JavaScript is client side scripting language.
    This one sentence contains three phrases that need further explanation:
    1. Client side: this means code that is under the responsibility of the browser (to differ from server side language such as PHP which is under the responsibility of the server)

      Client side code is under the responsibility of the browser and this means the code is executed on the client machine (the computer of the user visiting the website, to differ from server side code that is executed on the server machine) and it runs as part of the browser process.

      Client side has another important meaning: since it's executed by the browser itself, it becomes browser dependent. What does it mean? It means the same code might work on one browser and fail on other browser. (Sounds familiar?)
    2. Scripting: the scope of this is much bigger than this article but I'll try to describe it in short.

      Scripting language code is not compiled before it's executed, to differ from programming languages like C++ or Pascal or even .NET code.
      Scripting language has no .exe or .dll associated file, it consists of pure text file that is the whole code.

      Whenever scripting language code needs to execute, the RTE (Run Time Engine) loads the whole code into memory, compiles it "on the fly" and executes the commands in that code.
      For server side scripting languages like classic ASP or PHP, the RTE is part of the server itself while in client side code, the RTE is part of the browser.
      Being free of pre-compiling, scripting language does not have variable types. It simply does not need them, because the compiler does not need to allocate memory in advance for the code. It's all going to run on the memory "heap" anyway.
      With no variable types available, it's also not required to declare any variables in scripting language. Many see this as blessing (less code you know) but I see this as huge curse. (I'll elaborate in the next parts of the tutorial)
      Big advantage of scripting language is the ability to easily write code that write itself. It enables the programmer to do wonderful things, that are not possible in full scale programming languages.
      (More about it in the next parts - be tuned)
    3. JavaScript


    What is the meaning of the language name?
    It consist of two words:
    1. Java: Yes indeed, that's the famous programming language created by Sun corporation in the beginning of the 90's.
      How is it related? Syntax. The syntax of JavaScript is much alike to the syntax of Java.
      Apart of syntax, JavaScript is very far from being like Java: it does not have "class" files. It's not object oriented. JavaScript is FOP: Function Oriented Programming.
    2. Script: because JavaScript is Scripting Language with all the meanings explained above.

    This pretty much explains the name.

    Why JavaScript?
    For various reasons:
    • Being client side, it runs directly on the browser thus not bound to any server.
    • This is the only way to deal with client events, like mouse click or key press, in real time.
    • Client side form validation is essential part of any respectable website. The user will prefer to know of mistakes before the data is actually submitted to the server.
    • Cool things like image rollover are possible only with client side code.
    • Cool things like "live clock", simple games.
    • Just in case you need to mess with elements on the page during run time. For example, replacing the URL of all the links on the page in one go.


    How do I start?
    Under Windows OS click Start --> Run --> type "notepad" in the textbox and click OK.
    For non Windows OS just open your favorite text editor.
    Copy and paste the following code into the text editor:
    Code:
    <html>
    <head>
    <title>The Magic Of JavaScript</title>
    <script type="text/javascript">
        alert("hello world");
    </script>
    </head>
    <body>
    This page will eventually contain some nice things that can be done with JavaScript.
    </body>
    </html>
    Save the file under the name "nomagic.html" in your desktop.
    Double click the file to launch your default browser and execute it.
    If you have IE7 you'll have to click the yellow bar that appear on top of the contents and choose "Allow Blocked Content".
    You should see JavaScript alert box with the message "hello world".

    Congratulations! You've just wrote custom JavaScript code that is fully under your control.
    Keep tuned to this article to learn the real stuff.
    Coming next: Going Technical, Difference between JavaScript and VBScript and answer to questions.

    If you have any comments or questions, don't be shy! Post comment and say it.

    Tutorial Index
    Introduction to JavaScript
    Getting Technical With JavaScript

    Happy Programming!
    Last edited by Shadow Wizard; December 2nd, 2008 at 06:30 AM. Reason: added index
  2. #2
  3. Moderator From Beyond
    ASP Mastermind (5000+ posts)

    Join Date
    Sep 2004
    Location
    Israel
    Posts
    31,135
    Rep Power
    2922

    JavaScript Tutorial part II


    Getting Technical With JavaScript

    In this part we'll discuss ALF: Arrays, Loops and Functions, elements that are the heart of any programming language.

    I wish to thank Don for making this tutorial use the best language possible - I could not achieve this without you, Don!

    Arrays
    First, a quick reminder for those who forgot:
    • An array is a collection of items.
    • Each item in an array can be anything. (even another array)
    • An array can contain as many items as we want.
    • We can reference an item in an array by using its index in the array.
    • A basic array (and that's what we're going to discuss) does not support removing items, only adding them.

    JavaScript has two types of arrays. One is very common and shared by nearly all programming languages, and the second is less known and less used.

    The thing that distinguishes between those two types is the index. The common array has an integer index, meaning you reference an item using a numeric index and the second type of array can have anything as an index, including complex objects and elements. More on this below.
    1. Common Array: index starts from zero, meaning the first item in the array will have index of 0, the second item will have index of 1 etc. They say an example is worth a thousand words, here is a thousand words then:
      Code:
      <script type="text/javascript">
          var myFirstArray = new Array();
          myFirstArray[0] = "hello";
          myFirstArray[1] = "world";
          myFirstArray[2] = "how are you today?";
          alert(myFirstArray.join(" "));
      </script>
      Add that code to the file "nomagic.html" that you created in the first part of the tutorial, or create such file now. Execute it, and see what happens.

      The first line declares and creates instance of an array.

      The second line assigns the string "hello" to the first item of the array, the second line assigns another string to the second item and the next line assigns another string to the third item of the array.

      Finally, the last line shows an alert dialog with the array items Joined together: the "join" method works on array and returns all the items joined into a single string, with the given string as the separator. When a blank space is the separator the result you'll see is "hello world how are you today?"

      To count how many items an array contains, we can use the "length" property. Using the above, myFirstarray.length will return 3, because the array contains three items.

      To create an array out of a string (reverse action of join) use the "split" method of the string object. Thousand words:
      Code:
      <script type="text/javascript">
          var myString = "hello world how are you today?";
          var mySecondArray = myString.split(" ");
          alert("second array has " + mySecondArray.length + " items, which are:\n" + mySecondArray.join("\n"));
      </script>
      What happened here? I can bet you expected to get an array with three items, right?

      Well, the string "hello world how are you today?" contains five blank spaces. When used as the separator it means we have six items (words) that are separated, and the "split" method returns exactly those items. Each word in the sentence become an item in the array.

      How can I get specific a item from an array? The same way as assigning: using the index. Example:
      Code:
      <script type="text/javascript">
          var myThirdArray = new Array("hello", "world", "how are you today?");
          alert("second item in third array is: " + myThirdArray[1]);
      </script>
      That example contains yet another way to initialize an array and assign all its items at once by giving comma separated list of values to the array constructor.

      No surprise there, to get the second item we need to read the item with index of 1.

      Those three thousand words hopefully made you familiar (and more comfortable?) with the JavaScript Array, classic type.

      Now to the step-brother.
    2. I like to refer to this kind of array as a Collection, to distinguish it from the ordinary array described above.
      Unlike an ordinary array that only stores items, a collection can also store Keys: each Key has its own Value. This is achieved because the index can be anything, thus behaving as a key.
      An example will make it more clear:
      Code:
      <script type="text/javascript">
          var myFirstCollection = new Array();
          myFirstCollection["first key"] = "hello";
          myFirstCollection["second key"] = "world";
          myFirstCollection["third"] = "how are you today?";
          alert(myFirstCollection["second key"] + ", " + myFirstCollection["first key"] + ", " + myFirstCollection["third"]);
      </script>
      Instead of assigning the items using a numeric index, we assigned them using "name" of index. What is it good for? See the bottom of this tutorial part where the final example will make good use of this type of array.

      Important note: this kind of array has no "length" property, and also the "join" method won't work on it. Iterating over its items is more complicated than iterating over ordinary array items; the final example will show how this can be done.

    In JavaScript it's possible to reference array items that "does not exist", for example with the first array example myFirstArray[5] will give no exception, it will just give in return "undefined" value - so be careful.

    Loops
    Quick reminder:
    1. Loop in programming means repeating the same section of code over and over. The amount of repeats is called number of iterations.
    2. In order to perform such thing, we need to use variable that acts as the loop iterator and its value change in each iteration. When the value of the loop iterator is reaching the desired value the loop will stop.
    3. The value of a loop iterator can go up as well as it can go down: it does not matter, as long as it changes and there is the stop condition.
    4. The value of a loop iterator can change by more than one at each iteration.
    5. All programming languages allow breaking out of loop in the middle, meaning before the loop iterator has reached the desired value. For this purpose, each language has its own command.
    6. Common usage of loops can be printing multiply values related to each other e.g. all the days in month (loop from 1 to 31) and another very common usage of loop is iterating over array items.

    Now that we have this clear, it's time to see how JavaScript implements loops.
    Thousand words will make it crystal clear: (hopefully)
    Code:
    <script type="text/javascript">
        var myString = "";
        for (var i = 1; i <= 9; i++)
        {
            myString += i;
        }
        alert(myString);
    </script>
    What happened here? We iterated over the numbers 1 to 9, and in each iteration added the current number to string variable.

    The code inside the loop (that adds value to the string) was executed 9 times, because the initial value was 1 and the stop condition was when the loop iterator is bigger than 9. (More accurately, the loop was running as long as the loop iterator was equal or smaller than 9)

    As you see, a loop does not have to start from 0. It can start from anything you like (not ever a number!) and can end with any condition you like.

    Consider this code:
    Code:
    <script type="text/javascript">
        var myString = "";
        var dayMS = (1000 * 60 * 60 * 24);
        var dtIterator = new Date();
        var curMonth = dtIterator.getMonth();
        while (dtIterator.getMonth() == curMonth)
        {
            myString += dtIterator + "\n";
            dtIterator = new Date(dtIterator.getTime() + dayMS);
        }
        alert(myString);
    </script>
    This is another kind of loop, with different syntax but same logic. The loop iterator here is a variable with the name dtIterator. The initial value is the current date, and in every loop iteration we're adding one day to the loop iterator.
    When we reach the next month, we stop. Finally, we just show the dates from the current date to the last day of the month.
    The above just demonstrates that loop can have many forms, and the important part is that loop will always have section of code repeating itself and loop iterator that decides when the loop ends.

    That's it for now about loops: if you have any question or something you wish to know, just ask.

    Functions
    Function is block of code that can be called and executed from anywhere in the code, including from other functions.

    The block of code is wrapped inside the function, and you give name to that function, then in order to execute the wrapped code just use the name of the function.

    A function can get as many arguments as we like, and return one single return value, of any type. (Number, String, Date or even complex type)
    In JavaScript, function also act as class: it can wrap its own properties and methods. This is not commonly known though.
    Classic example is function that is getting two numbers as input (arguments) and returns the sum of those two numbers:
    Code:
    <script type="text/javascript">
        function MyFirstFunction(num1, num2)
        {
            return num1 + num2;
        }
        alert(MyFirstFunction(10, 20));
    </script>
    As expected, you'll see dialog box with the number 30: our first function has two arguments: num1 and num2, and is returning the sum of those arguments.

    Now I'm going to introduce the other side: using functions as classes in JavaScript. Here you go:
    Code:
    <script type="text/javascript">
        function Car(strModel, strColor, nInitialMileage)
        {
            this.model = strModel;
            this.color = strColor;
            this.mileage = nInitialMileage;
            
            this.Drive = function CarDrive(nMilesCount)
            {
                this.mileage += nMilesCount;
            }
    
            this.GetModel = function CarGetModel()
            {
                return this.model;
            }
    
            
            this.GetColor = function CarGetColor()
            {
                return this.color;
            }
    
            this.GetCurrentMileage = function CarGetMileage()
            {
                return this.mileage;
            }
        }
        
        var myFirstCar = new Car("Volvo", "black", 1500);
        var mySecondCar = new Car("Jaguar", "metallic blue", 12500);
        myFirstCar.Drive(500);
        alert("my first car is " + myFirstCar.GetModel() + " and it drove total of " + myFirstCar.GetCurrentMileage() + " miles and my second car color is " + mySecondCar.GetColor() + " and it's mileage is " + mySecondCar.GetCurrentMileage());
    </script>
    What happened here? Don't worry, it's no magic so I'll explain step by step.
    1. We created function called Car. Like with any function, it can be called from anywhere in the code and we can give it arguments. However, this function has different purpose. It does not return anything, but rather defines a car object.
    2. The function has three arguments, defining several properties of the car we wish to create.
    3. By using the keyword this inside the function we actually make is a class and cause the value we store to become global in the instance of the class we just created.
    4. We have defined three properties of the car object, and four methods. The properties are the car model, color and mileage. One method is Drive: it gets amount of miles the car has driven and is updating the mileage of the car accordingly. The other three methods only return the value of the car properties, exposing them to the outside world.
    5. JavaScript is pretty special in the fact it allows "function inside function": this is very powerful approach, using it in order to define class methods inside the function defining the class itself is one small example.
    6. Having the class at hand, we created two instances of that class, each with its own data. myFirstCar and mySecondCar holds two separate instances of the class, each sit in its own memory block.
    7. We used the Drive method to change the mileage of the first car.
    8. Finally, showing the data from both cars to prove something happened there.

    That's it... you're now familiar with functions in JavaScript. Feel free to ask any question you like about it, I know you have questions. If you don't have any question it means you didn't read hard enough!

    As a bonus for those reading so far down the page, here is code that combines all the three parts of ALF to do something cool. Just copy into NoMagic.html and execute!
    Code:
    <script type="text/javascript">
        function MyFirstCoolFunction(someString)
        {
            var arrFuncReturnValue = new Array();
            for (var i = 0; i < someString.length; i++)
            {
                var curChar = someString.substr(i, 1);
                if (typeof arrFuncReturnValue[curChar] == "undefined")
                {
                    arrFuncReturnValue[curChar] = 0;
                }
                arrFuncReturnValue[curChar]++;
            }
            return arrFuncReturnValue;
        }
        var myArray = MyFirstCoolFunction("hello world, how are you today? Wonder what is going to happen...");
        var sMessage = "";
        for (var character in myArray)
        {
            sMessage += "The character " + character + " appeared in the string " + myArray[character] + " times.\n";
        }
        alert(sMessage);
    </script>
    We combined arrays, loops and functions to create something that might have actual use one day: counting how many times each character appears in a given string.



    Coming next: Interacting with the user, if..then tutorial and maybe some more details about stuff we've already learned.

    If you have any comments or questions, don't be shy! Post comment and say it.

    Tutorial Index
    Introduction to JavaScript
    Getting Technical With JavaScript

    Happy Programming!
    Last edited by Shadow Wizard; December 2nd, 2008 at 06:31 AM. Reason: added tutorial index

Similar Threads

  1. Javascript to compare asp dropdownlist
    By peebman2000 in forum HTML, JavaScript And CSS Help
    Replies: 1
    Last Post: March 16th, 2007, 04:52 PM
  2. Figuring out the CMS ASP Tutorial
    By Hambone in forum ASP Development
    Replies: 3
    Last Post: September 19th, 2006, 09:49 AM
  3. Multiple variables to javascript in ASP.net
    By RevJuice in forum .NET Development
    Replies: 1
    Last Post: June 20th, 2006, 01:40 PM
  4. javascript free tutorial
    By velajus in forum HTML, JavaScript And CSS Help
    Replies: 3
    Last Post: June 7th, 2005, 06:29 AM
  5. how to prevent javascript menu from being hidden back by <iframe>
    By arif_1947 in forum HTML, JavaScript And CSS Help
    Replies: 6
    Last Post: March 31st, 2005, 05:06 PM

IMN logo majestic logo threadwatch logo seochat tools logo