Intro to Coding: Concepts and Examples (JavaScript)

null

and void
|K3| Member
TABLE OF CONTENTS
LINE 1 - THIS POST
LINE 2 - http://krewgaming.com/threads/10776/#post-185065

I was talking with some Krew members after a match on a1 a few weeks ago and the subject of interests/professions came up. When I mentioned that I'm a developer, someone (my apologies for forgetting who) suggested that I consider writing a series of tutorials for the benefit of members interested in learning how to code.

Of course I was honored by the request since it presumes I have knowledge worth sharing, however *I* don't presume that my presentation of that knowledge would be demonstrably better than any of the many tutorials already out there (and in many cases I'm sure it would be far worse). But, reservations aside, I liked the idea and so have been thinking about it since; looking for some project or example to use as a 'starting point.'

As luck would have it, I found myself wanting a bit of a puzzle last night and the shoutbox thread presented the perfect excuse to write something. Several of you have been able to make use of that work (awesome!) and since I firmly believe that practical examples are the best, it seems to me as though a 'starting point' has fallen into place.

I'd like to use this thread to discuss what's happening, in a line-by-line analysis, in the simplest version of the shoutbox script, and to answer any questions people may have about some aspect of the code. Further, I invite @Kreubs to expand on any points, answer questions, &c. &c. however he sees fit. If there's good interest in this, perhaps another thread can be started to discuss further problems and examples, and other programming languages - let me know.

To begin, here is the JavaScript code that we will be discussing:
Code:
function taigaRemoveThreads() {
    var messages = document.getElementById('taigachat_box').getElementsByTagName('li');
    for (var i = 0; i < messages.length; i++) {
        if (messages[i].innerHTML.indexOf('internalLink') > 0) {
            messages[i].style.display = 'none';
        }
    } setTimeout(function () { taigaRemoveThreads(); }, 100);
} taigaRemoveThreads();

You may notice that I have removed the // ==UserScript== section from the top of this: that section is merely added for the benefit of utilities like Greasemonkey and only contains metadata about the script (i.e. no code).

Donald Knuth, a very important CS figure/prof., has a method called 'literate programming' which seeks to define programs using plain English. Here is the above script written literally:
Code:
Define a block of code that takes no arguments and can be referenced as taigaRemoveThreads
    Create a variable called messages that contains all of the <li> elements in the 'taigachat_box' HTML <div>
        For each of the <li> items in the messages variable, do the following:
            If the current <li> item contains the text 'internalLink', do the following:
                Set the CSS 'display' property of this <li> element to 'none' to hide it.
            Move to the next <li> item.
        Stop processing the <li> items in messages.
    In 100 milliseconds, do the following:
        Create a new reference to taigaRemoveThreads, causing the function to execute again.
    Stop the timer.
End the taigaRemoveThreads block.
Call the taigaRemoveThreads function, causing it to execute the first time.

Line 1:
Code:
function taigaRemoveThreads() {

The first word we encounter is function. What does that mean? It is perhaps obvious, but we must first realize that, in addition to there being very many programming languages, there are many ways in which we can write programs - something called 'style.'

Of course different languages elect to use different styles, depending on the preferences and goals of the language's developer(s). So, what are these styles? For the sake of brevity (for there are many), the *main* ones are:
1) procedural
2) functional
3) object-oriented (which we'll talk about another time perhaps?)

I have taken care to present these styles in rough order of increasing complexity (functional languages that delve into recursion theory (which I'd enjoy talking about at some point) can become highly complex). Let's have a look at, at their most basic, these styles mean:

1) Procedural code is written in a way that is meant to be executed line after line, in a perfect, generally non-repeating, sequence from the top of the file to the bottom. The classic example of this is a program written in the BASIC language:
Code:
10 CLS
20 PRINT "HELLO, WORLD"
30 END

As you can see, we start at the top of the file and clear the screen (CLS). Next, we print the message "HELLO, WORLD" (PRINT) then halt the program (END).

2) So what about functional code? Language designers realized that there may be certain BLOCKS of code that you want to use several times during the course of your program. Now, procedural languages like BASIC address this desire somewhat by implementing a command like GOTO. The problem is that, if you use GOTO a lot, things can quickly become very confusing and cross-referenced (something programmers call 'spaghetti code').

How can we solve that? By using something called a ... function. Put simply, a function contains a block of code that will be executed each time the function is called. Inside of the function the code may still be written procedurally, i.e. start at the first line in the function and proceed to the bottom line, but the function itself can be called at any time. Pretty useful.

So THAT is what function means in our first line! What's about to follow is a block of code that we can execute EVERY time we call it! But how do we call it? How does the code know that we want to use this particular function? "A man needs a name..."

The second word we encounter is taigaRemoveThreads. This is the NAME of our function! Now, every time we want to execute this particular block of code we can simply write 'taigaRemoveThreads()' - very cool!

Hold on, though: What about those parentheses? Are those part of the name? You didn't mention those the first time! No, the parentheses are not part of the name, but they do have a special purpose.

It's very cool that our function can execute a block of code on demand, but what if we want to, say, transform some data by passing it through a function - how can the function 'see' that data? Here again we could delve very deeply into a conversation about scoping - that is to say, what data the various parts of your program have access to.

To keep things simple, however, let's assume that the function can only see what is inside of itself. If we want the function to know about some EXTERNAL data, we have to pass it to the function. THIS is what the parentheses are for: they contain what programmers call 'arguments.'

Let's have an example. Say I'm writing a program that says "HELLO, NAME!". Instead of name, however, I want to actually write my users' names. If I did this procedurally then I'd have to write a line for EVERY user, something like:
Code:
10 PRINT "HELLO, BOB!"
20 PRINT "HELLO, ALICE!"
30 PRINT "HELLO, EVE!"

Yuck. So let's try using a function instead:
Code:
function sayHello() {
    console.log("HELLO, NAME!");
}

Cool. Now we can just write 'sayHello()' every time we want to say hello to a user...but it only says 'NAME' not the user's name like we want. Okay, you say, we can solve that procedurally...but now we're right back to the BASIC example. We somehow need to *pass* some data INTO the function. Aha! We'll use an *argument*! Let's try that function again:
Code:
function sayHello(name) {
    console.log("HELLO, " + name = "!");
}

Okay, now a few things have changed. First of all, we have a new word between the parentheses: 'name'. Now, when we call 'sayHello' we can include external data (i.e. a name) like this: sayHello("KREW");. The value "KREW" will be assigned to the variable 'name' for use INSIDE our function! Nice!

But wait - I thought you said 'name' was an argument but now you're calling it a variable? What gives? When we ASSIGN a value to 'name' by including it in the call to our sayHello function, then it is called an ARGUMENT (arguments are passed). Yet when we USE 'name' within our function, then it is called a VARIABLE (variables are referenced).

What else has changed? In both versions, we have used the 'console.log' command. In JavaScript, this is a command that takes text as an ARGUMENT and writes it out to the console built into your browser (check it out by hitting F12). So, what we're writing in the parentheses is an example of the arguments we were just talking about!

Let's see … we've got quotes - okay, so we're defining what the text is. But then we've got plus signs? What are those? Programming has another concept called 'concatenation' - and that's what's happening here. Put simply, concatenation is taking two or more things and putting them together into one thing. In this case, we know that we want to write "HELLO, KREW!" but the "KREW" part of that is VARIABLE - it is going to change. Therefore, we need to write a FIXED string (in programming a 'string' is a PIECE of data that will be treated as text) and CONCATENATE a variable onto it. Since the exclamation point is similarly fixed, we can concatenate a final string into the end of this structure. Hence: "HELLO, " + name + "!". I.e. write this fixed string, concatenate a variable onto it, then concatenate a final fixed string.

Returning to our main topic, now we know what the parentheses are all about, and we can see that this particular function (taigaRemoveThreads) isn't taking any arguments.

So - what's left on this line? Well, lastly we see a single open curly brace ("{"). Here again we could have a very deep conversation about something called 'syntax' and 'syntactic sugar' - terms that basically refer to the SYMBOLS and FORMATTING a language uses to convey meaning. Once again, each language implements syntax in a way that makes the most sense to its developer(s) or for its purpose (for example Texas Instruments implements a very sparse native BASIC on their calculators because you wouldn't want to type much more on such a little 'keyboard').

JavaScript is a little notorious for its overly-verbose, sometimes inconsistent, syntax. One of the rules is that, to define WHAT is contained WITHIN a function, the code must be enclosed within curly braces. So this opening brace is saying "the code that I want to be executed when this function is called starts here." Correspondingly, then, when we get to the close brace we're saying "the code that I want to be executed when this function is called ends here."

THAT'S LINE 1!

What do you guys think? Should I keep going like this? Was it interesting?
 
Last edited:

HIBred

Foolish Mortal
|K3| Executive
This is waaaay over my head but I'm sure a lot will find it useful and interesting,I know some members have delved into coding a little, as for me it sounds like this

but thanks man :)
 

miniCyb3r

Slave to nothing.
|K3| Member
Wat8.jpg
 

Ethan

Captain
Former Krew Member
I'm planning to pursue Business Administration in college, specifically in the IT area. Think I'll have to learn any of this?
 

null

and void
|K3| Member
@HIBred & @miniCyb3r Hahaha, my sincere apologies chaps. A lot of tutorials walk you though writing a particular piece of code, but in my mind they never address WHY you're writing the code that way. To bring something new to the table, I tried to introduce concepts first. Perhaps this was a little overly ambitious…

@Ethan That's certainly a good question. As a programmer I can tell you that, were you *my* manager and you knew at least some of this stuff - enough so that, were there some problem, delay or subtle complexity in meeting a goal, I could explain things to you and you would understand - you'd earn a lot more of my respect; and more quickly to boot.

That said, your course will likely only introduce these concepts to you in a very basic way and the majority of your peers will forget them before they even graduate. There are 3 possibilities:
1) The programming courses are handled within the Business school by its professors. This is terrible. It's also the easiest.
2) The courses are handled by CSCI professors, but are specifically for Business students. This is bad, but not terrible. It's fairly easy.
3) The courses are part of the CSCI curriculum and you'll be with freshman/sophomore CSCI majors. This is the best but varies in difficulty.​

The point is that it will be some work, and it's work that - depending on your program - most of your peers may not be doing. So, let's look at your return on investment:
Negative:
1) You will have to put in more work than your peers.
2) You will be practicing a skill set that you do not utilize every day. (In fact, I would discourage you from ever writing code directly.)​

Positive:
1) You will have more specific knowledge than most of your peers.
2) Engineers and programmers will WANT to explain things to you = happier/more productive staff.
3) You will be in a unique position to translate the frustrations of management and the frustrations of your programmers/team.
4) You will know when someone on your team is bullshitting you.​

The point isn't that you can write the code; it's that you can understand what your team is saying. If that seems like a value-add to you then I suggest looking into these topics. Again, it all really depends on your program and in that regard YMMV. Hope this helps.
 

NickHouston

WaLLy's Personal Favorite Krew Member
|K3| Member
|K3| Media Team
I started trying to teach myself some simple Javascript/HTML about a year ago. I got very discouraged because the website would introduce something, then not have you use it until 4 sections later. I ultimately got annoyed and quit.

I'm going to be taking a web design class(building a website from scratch). I'll probably be in HTML though, not Javascript. Can both be used together?
 

null

and void
|K3| Member
@NickHouston Interesting. Did you find this tutorial annoying for the same reason? I realize now that, while going through things line-by-line allows for maximum exposition, there's still a 'wtf does this mean?' aspect.

Donald Knuth (important CS prof.) has a practice called 'literate programming' that seeks to write code in plain English. I am going to do that for this tutorial, both as its own post and edited in to the OP to hopefully add another level of comprehensibility.

To answer your question directly: absolutely. In fact, the script I wrote reads the page HTML and modifies CSS rules to hide certain elements - so you see you can manipulate a page's CSS as well.

There are whole JavaScript frameworks now for writing web applications: Angular and Ember, for example.

Do you remember what tutorial you used originally? I'd be curious to look at it.
[DOUBLEPOST=1424573687][/DOUBLEPOST]As promised, here is the tutorial script written literally (I have edited it into the OP as well). Hopefully this adds an additional level of clarity:
Code:
Define a block of code that takes no arguments and can be referenced as taigaRemoveThreads
    Create a variable called messages that contains all of the <li> elements in the 'taigachat_box' HTML <div>
        For each of the <li> items in the messages variable, do the following:
            If the current <li> item contains the text 'internalLink', do the following:
                Set the CSS 'display' property of this <li> element to 'none' to hide it.
            Move to the next <li> item.
        Stop processing the <li> items in messages.
    In 100 milliseconds, do the following:
        Create a new reference to taigaRemoveThreads, causing the function to execute again.
    Stop the timer.
End the taigaRemoveThreads block.
Call the taigaRemoveThreads function, causing it to execute the first time.
 
Last edited:

NickHouston

WaLLy's Personal Favorite Krew Member
|K3| Member
|K3| Media Team
@NickHouston Interesting. Did you find this tutorial annoying for the same reason? I realize now that, while going through things line-by-line allows for maximum exposition, there's still a 'wtf does this mean?' aspect.

Donald Knuth (important CS prof.) has a practice called 'literate programming' that seeks to write code in plain English. I am going to do that for this tutorial, both as its own post and edited in to the OP to hopefully add another level of comprehensibility.

To answer your question directly: absolutely. In fact, the script I wrote reads the page HTML and modifies CSS rules to hide certain elements - so you see you can manipulate a page's CSS as well.

There are whole JavaScript frameworks now for writing web applications: Angular and Ember, for example.

Do you remember what tutorial you used originally? I'd be curious to look at it.
[DOUBLEPOST=1424573687][/DOUBLEPOST]As promised, here is the tutorial script written literally (I have edited it into the OP as well). Hopefully this adds an additional level of clarity:
Code:
Define a block of code that takes no arguments and can be referenced as taigaRemoveThreads
    Create a variable called messages that contains all of the <li> elements in the 'taigachat_box' HTML <div>
        For each of the <li> items in the messages variable, do the following:
            If the current <li> item contains the text 'internalLink', do the following:
                Set the CSS 'display' property of this <li> element to 'none' to hide it.
            Move to the next <li> item.
        Stop processing the <li> items in messages.
    In 100 milliseconds, do the following:
        Create a new reference to taigaRemoveThreads, causing the function to execute again.
    Stop the timer.
End the taigaRemoveThreads block.
Call the taigaRemoveThreads function, causing it to execute the first time.

Your tutorial was actually great!

I used codecademy.com. It's a good service but they let you have time to forget a skill before using it.
 

Madeinkorea

|KKK|'s Lagger
|K3| Member
This tutorial was very helpful, especially as a transition from Python to Java. I really enjoyed this, and can't wait for more in depth discussions. I'm planning on majoring in Computer Engineering, and I'd really like learning how and why the code works the way it does.
 

Storky

Rawr
|K3| Moderator
Recruitment Team
This is good. Programming is a good skill to have!

Ask me anything about Python :D.

I think JavaScript is an evil language though ;)
 

DamageINC

K3's Useless Admin
|K3| Executive
I programmed my Logitech harmony to control four devices. Pretty proud of that. Took me awhile, but i got it done. TWICE!
 

null

and void
|K3| Member
@Garycheese Don't be discouraged. I'm not sure if this applies to you, but I think one reason people find programming difficult is because they look at it as though there are all these very specialized bits to memorize - in exactly such and such particular way - and you just have to "know it" to be able to do it. I'd argue, however, that programming is NOT about WRITING programs: that's just the END result. In my mind, programming is THINKING about a problem in a language/logic structure that the computer understands, then MODELING your solution using that language. This is a very important distinction. In fact, there are very few NEW mechanisms when it comes to programming: most languages share basic structures (if, then, else, for, while, variables, operators (+, -, <, >, <=, >=, =, ==, !=, ^, /, *, etc.), functions, etc.). What this means is that, when you learn to THINK in one language - using those basic structures to MODEL your problem - you can pick up most ANY language with a little practice. So to those looking to learn programming/coding: don't try to MEMORIZE solutions, try to THINK about problems.

And now, on to line 2…

Line 2:

JavaScript:
Code:
var messages = document.getElementById('taigachat_box').getElementsByTagName('li');

Literate:
Code:
Create a variable called messages that contains all of the <li> elements in the 'taigachat_box' HTML <div>

Discussion:
I'm very happy we've got the literate code now - I think it frames these futher lines (which are more complicated) much more clearly! Using the same structure as previously, let's have a look at the first word: var.

Var is, perhaps obviously, short for the word variable. In CS, a variable is an OBJECT (we'll get to what this means in a moment) that CONTAINS some data. That data can then be REFERENCED or UPDATED elsewhere in our program. Well, that's obviously useful but how does a variable really work?

Let's think about what a computer really is: We can think of a computer as containing a table, where each cell of the table equates to a little piece of memory. These cells are called 'registers' and they hold 1s and 0s. When the computer wants to perform some operation, it takes one or more of these registers and does something to them, then stores the result in new (empty) registers or over the top of the original register(s). In a nutshell, this is effectively how EVERYTHING in a computer works. If this topic interests you, I highly recommend watching this video:


Now, some really hardcore people might like to program their computers in this very basic way - but it would be a long and difficult process. Computer scientists realized just how awful programming in 1s and 0s would be, so they invented programming languages (for more on this, read about Grace Hopper and John McCarthy). Yet what is a programming language? Put simply, a programming language is a set of human understandable symbols and words that are translated into machine understandable 1s and 0s, and the operations the computer should take on those 1s and 0s - that's it!

So programming languages are ABSTRACTIONS of binary storage and operations, modeled in ways that are friendlier for people. In part 1 we discussed how there were very many languages; well, there are also different levels of abstraction between languages - programmers call these low-level languages (or "close to the metal") and high-level languages. Examples: the C language is considered a lower-level language and JavaScript a high-level language. This is because C code more closely resembles the binary operations the computer performs than JavaScript code (more on this soon).

Right, so we've got some level of abstraction happening through something called a programming language. This is great! Yet although our language abstracts complexity away, it is still bound by the rules of the computer system; that is, the computer still operates on 1s and 0s.

Moving back to variables: what could that REALLY mean? Well, the role of a variable is to have the computer SELECT an empty memory register and STORE a value in it for future REFERENCE.

A high-level language like JavaScript will do this entire process for you - it's simple: just tell the language you want a variable. A lower-level language like C actually has you assign your own memory registers, manage which ones have values, and clear registers you no longer need (something called 'garbage collection') - this makes C more difficult, but if you know what you're doing MUCH faster (and able to work with less memory).

Okay - so if we want to store a value in memory using JavaScript, since it's high-level, the language will handle finding an empty memory register and writing to it automatically. So, we declare a var. That one word does ALL of the abstraction. Pretty cool, huh? So that's what the first word is doing.

Now, when I said a variable stores an OBJECT what did that mean? What is an object? Objects in programming mean something very specific. In this case, the object has to do with the types of DATA STRUCTURES our language allows us to define. Huh?

Consider that - as we've said before - the computer understands only 1s and 0s. Therefore, the computer DOES NOT KNOW the difference between a letter or a number - it doesn't know anything except 1 and 0. People do, however. So if we're going to abstract away the complexity of using 1s and 0s, and do so in a way that makes sense to people, doesn't it make sense that we should at least make our LANGUAGE aware of these different 'types' of information? A number is a number, a word a word, etc.

So language designers implemented something called a 'type system' that makes sure the values you're putting into your variables MAKE SENSE for the 'type' of data you're saying they contain. Why? Well, first of all so that you can keep things straight in your head. But secondly because there are SPECIFIC actions you may want to take on words that you wouldn't want to take on numbers. Type systems help with that.

So what are the most common types? They are: integers, strings, arrays and booleans. A variable can contain ANY of these types and in that regard, since the variable INHERITS the properties of the type of value it contains, it is considered an OBJECT; a pure container of data (the variable is agnostic: it does not care WHAT type you put in it).

Great, so we know WHAT a variable is trying to do, and why it's called an object. We want to USE this variable in our program, but now we have the same problem we did when we were creating functions - that is, how can we REFERENCE this variable? How does the computer know when we want to use it? "A man needs a name..."

Word 2: messages. Aha! That's the NAME of our variable! So, whenever we want to access the particular memory register that contains a certain TYPE of data that we have ASSIGNED to it, rather than having to use some obscure memory location name that the machine understands, our language has abstracted things such that we can simply write messages!

Great, so we're having the computer find a register that we can use, name it something easy for us to remember, now we want to ASSIGN a value to it. How do we do that?

Word 3: =. Equals! Ahhh. So we want the variable to EQUAL (i.e. contain) what's about to follow (to the right of the symbol). In this way it's just like math! I.e. x = 3!

Now we know how to declare a variable in JavaScript - so, let's get assigning! Now, for this particular script we want to remove certain elements from the Taiga Pro chat window. If you inspect the HTML code, you'll see that the Taiga software renders each message in an HTML <li> tag. You'll further see that each of these <li> items is contained within a single <div> element that has an 'id' of taigachat_box.

So the very first thing we'll want to do is STORE all of those <li> items inside of the taigachat_box <div> so that we can use them later.

Now we're getting fully into the abstractions JavaScript has built-in for reading and manipulating the DOM (document object model); that's a scary acronym that basically equates to the page's HTML code.

We know that the <li> items are INSIDE of the taigachat_box <div>, so we first need to GET the contents of that <div>.

Word 4: document.getElementbyId('taigachat_box'). And here's where the magic is happening. The 'document' word is shorthand for the DOM - the page's HTML - so we're saying "Look inside the HTML code of this page." Next, we're using 'getElementById' which is saying "Now that you have the HTML code of this page, look for an HTML element that has a particular id." Finally, we have an ARGUMENT (remember those?) that tells the program WHICH particular id we're looking for: "The particular id I'm looking for is called 'taigachat_box.' And just like that we have selected the HTML code INSIDE of the 'taigachat_box' div - by successively whittling things down starting at the root of the HTML document.

Great - we have the HTML inside of the right <div>, but we don't want ALL of that stuff. As we said before, the messages are written inside of <li> tags, so we really only want those. Well, JavaScript has yet another abstraction we can use to do that.

Word 5: getElementsByTagName('li'). So now what we're doing is whittling things even further. We're saying "now that you have the HTML inside of the right div, I ONLY want you to select the HTML elements that have this particular tag." Here again the code takes arguments - saying "And that particular tag is called 'li'."

And there you have it. JavaScript allows you to to chain arbitrarily many of these abstractions (by attaching them with period ".") to whittle a set of HTML elements down to JUST the ones that you want.

We have started at the root of the document, descended into a particular <div>, then further refined those results to only fetch <li> elements. Then, we STORED those <li> elements (as an array!) in a variable (new memory register) called 'messages'!

THAT'S LINE 2!
 
Last edited:
Top Bottom