1. This website uses cookies. By continuing to use this website you are giving consent to cookies being used.
    For information on cookies and how you can disable them visit our Cookie Usage page.
    Dismiss Notice

[JavaScript] Introduction

Discussion in 'Web Development' started by Farodin, Oct 25, 2014.

?

Was this introduction...

  1. helpful

    0 vote(s)
    0.0%
  2. easy to understand

    1 vote(s)
    100.0%
  3. neither

    0 vote(s)
    0.0%
Multiple votes are allowed.
  1. Farodin

    Farodin New Member

    If you've dealt with websites, chances are you already heard about 'JavaScript' and how it makes websites 'more interactive'. But what actually is it, and how does it work?

    Without going into too technical details, JavaScript is a scripting language mainly for browsers (Firefox, Internet Explorer, Chrome, Opera, Safari, etc.). The difference between a scripting language and a programming language is, that a scripting language is supplemental to an existing program. A browser for example can easily display websites without any JavaScript at all.
    Originally developed under the name 'Mocha', Netscape released it in their beta version of Netscape Navigator 2.0 in 1995 under the name of 'LiveScript' but later renamed it to today's name of 'JavaScript'.

    In order to work inside a browser and be able to actually change things on a website, JavaScript (from here on abbreviated to JS) accesses the Document Object Model (DOM). Every element (object) on a website is part of the DOM tree (tree because it has a tree-like structure) which starts with the object 'document' (thus 'document' - 'object' - Model). JS is an object-oriented language (OOP) to the core, understanding how objects work makes life a lot easier.

    Note:
    I'm assuming a very basic concept with C-like programming languages, words like variables, functions and return values should be known, otherwise it would make more sense to read up on what a programming language is and how it works first.
    Also, if you want to try these things yourself, you can just hit F12 in most modern browsers and get to the console, the line where you can enter your command usually has a symbol that looks like this: >

    Lets start easy:

    Code:
    thing = 5;
    thing = function test() {};
    thing = {a:5,b:2,c:7};
    
    Here we have the variable 'thing' that first gets assigned a number, then a function and finally an object with the 3 items a, b and c.
    if you would ask JS what type 'thing' is after each statement - typeof(thing) - , the answers would be 'number', 'function', 'object'.
    Objects can have properties and methods, which can be accessed using a dot between the names. A property would be another variable like a,b,c in the 3rd statement. A method would be a function.
    Code:
    thing = {a:5,b:2,c:7,d:function test() {}};
    
    Now we have 3 properties and one method for the object 'thing' which are a,b,c and d. If we now type in
    Code:
    thing.a
    thing.b
    thing.c
    thing.d
    
    the results would be
    Code:
    5
    2
    7
    test()
    
    You have just accessed the properties and the method of 'thing'. You could now go ahead and nest objects inside 'thing' like this:
    Code:
    thing = {a:5,b:2,c:7,d:function test() {},e:{k:1,l:{q:6}}};
    
    Now this is really hard to read, so let's make it more human readable
    Code:
    thing = {
        a: 5,
        b: 2,
        c: 7,
        d: function test() {},
        e: {
            k:1,
            l: {
                q:6
            }
        }
    };
    
    Better, now in order to get to the value of q, you would have to enter
    Code:
    thing.e.l.q
    
    which would give you the '6' you've been looking for.
    This is a way of accessing properties of an object, you can also use brackets, in fact you have to use them if the name of the property includes special characters like this:
    Code:
    thing = {'b-c':5}
    
    In order to access 'b-c' you would have to write
    Code:
    thing['b-c']
    
    This should feel familiar for those that have worked with PHP and arrays before.
    To demonstrate why 'thing.b-c' doesn't work, lets try this:
    Code:
    thing = {b:5,'b-c':9}
    c = 3
    thing.b-c
    
    The result will be '2'.
    For JavaScript the symbol '-' is an operator and in this case meant "deduct the value of c from the value of thing.b" which translates to "5 - 3" which is 2.

    Now as for methods, lets have a look at the following:
    Code:
    function thing() {
      this.a = function() {
        return 5;
      }
      return this;
    }
    
    There is another way of achieving something similar:
    Code:
    function thing() {
      return this;
    }
    
    thing.prototype.a = function() {
      return 5;
    }
    
    In both cases you can type in
    Code:
    thing().a();
    
    and would get '5' as the result. In order for you to just have to type thing.a() or something like thing.j.p.s.a(), each object ('thing','j','p','s') would have to return another object and the last one ('s') would have to have the method 'a'.
    Now, there are 3 new things here, 'this', 'return' and prototype'.
    'return' is pretty easy, you call a function and you can get something back in return, in the case of function 'a', you get the number 5.
    'this' is a special variable that always points to the currently active scope. A scope is the area inside a program where something is valid. For example
    Code:
    function thing() {
      var a = 5;
    }
    
    'var' tells JS that the variable a is only valid in the currently active scope. The active scope is the function 'thing', identified by the symbols '{' and '}'. Everything within these is the scope of the function. If you would now try to access 'a' afterwards, JS would tell you that its undefined, because the currently active scope did not define 'a'.
    If something is not inside any particular scope, it is always automatically in the scope of 'window', you can always add 'window.' in front of anything and it should work just the same.
    Try it, if your last entry in the console was 'thing().a()', you can now try 'window.thing().a()' and it should say '5' as well.
    Now, in order to explain 'prototype', I need to explain an instance first.
    In JavaScript you can create an instance of any object by typing in 'new' followed by whatever object you want to instantiate. You would do that if you need the same structure of an object for different things.
    For example you have two persons, person a is 24 years old, person b is 27. If you only had one object 'person' you couldn't store both ages under 'person.age'. What you could do is instantiate 'person' for each one like this:
    Code:
    function person() {
      this.age = 0;
    }
    
    hans = new person;
    stacy = new person;
    
    hans.age = 27;
    stacy.age = 24;
    
    But what if you now wanted to add a function that returns the age? You already have two instances of 'person' and would have to re-create them if you wanted to add the method to 'person'. That's where 'prototype' comes in.
    Code:
    person.prototype.getAge = function() {
      return this.age;
    }
    
    If you now type in 'hans.getAge()' you will get '27' as return value.
    Now obviously you would never have the situation that you have to add a method to a function you wrote yourself. However you could use it to add methods to a function someone else wrote in a script you included on your site without tinkering with the script itself.
    One thing you could, but really shouldn't do, is adding methods to the pre-defined objects:
    Code:
    Object.prototype.getFive = function() {return 5};
    
    Now you can type in the name of any existing object it will have that method
    Code:
    hans.getFive()
    person.getFive()
    window.getFive()
    document.getFive()
    
    You will always get '5' back. This is something you can do if you are 100% certain nobody else will ever have to deal with your code (that means you are not using anyone else's code and nobody else is using your code), however if that is not guaranteed, you should avoid using 'prototype' on pre-defined objects. The reason for this is simple, someone else should be able to rely on those pre-defined objects to be as they are without any modifications. If they are not, the code may break or behave strangely.

    If you happen to use classes in languages like Java or PHP and are used to having constructors, there is a great answer for that in JS too.


    And that concludes this post about the basics of JS, I hope it was somewhat helpful.
    If there are any questions, I'd be happy to answer them.
    Also if there is something specific about JS that I should write about, please let me know as well :)
    Otherwise the next one would be about dealing with the DOM.