Computer programming is writing instructions for a computer to execute. We have seen some computer languages in making websites so far, but, strictly speaking, these may not be considered programming languages, because they lack a key component: a sequential flow of logical and mathematical instructions. We have described which text we want the web page to have and how it should look, but we have not given a series of steps to be executed.
Computer programs are actually analogous to flow charts. Really, they are exactly like flow charts, except that they give instructions in terms of what computers can do vs. what humans can do, and they are usually much larger and more intricate than flow charts you would have seen in school. In fact, in the early days of computer science, before it was even called computer science, there was a confusion about what to call its experts. Some called them flow-charts-men.
So, when we want to tell the computer what to do, we need to speak in a language it can understand and give it instructions which it is capable of following. Using this language and this knowledge, we effectively construct a flow chart which covers situations such as "ask the user his/her age", "do [this] if the user enters 18+ for his age", or "do [this] when the user clicks on this button".
Before we go further, it may help to see an example of what we are talking about, even if you don't understand it yet:
Basically all programming languages have basic, primordial tools with which you can read text input and write text output. In non-Web languages, like C and C++, you might start by writing DOS-like programs, which are keyboard-only. We will use a website environment to replicate this: we will have an area for basic text input and an area for basic text output.
A variable is a named container of information. Its motivation is simple: if you want to ask the user for his/her age, or his/her height or weight, you want to store that information somewhere and give it a name so that you can refer to it later. So you might make variables called userAge, userHeight, or userWeight. You can also use variables to contain the results of your own computation. For example, this snippet declares a few variables and does some arithmetic, which we will explore later:
You may notice that variables tend to have a distinct naming pattern. There are a few rules which govern the naming of variables, all of which explain what you cannot do. Basically, you cannot begin a variable name with a number; you cannot use a symbol inside the name except for the underscore (_), and you cannot have any spaces inside the name. This is true for nearly all programming languages and you can safely assume these rules when learning a new language.
Beyond that, you can name the variable according to your own styles, though there are a few common choices:
Declaring a variable is the act of announcing that the variable exists; "this variable exists as of now". When you declare a variable, you often need some additional syntax to signify the declaration.
Notice that var was only used once per each variable, when they were introduced. In the subsequent uses of those variables, the word var did not precede them.
In order to convert a textual version of a number to a numeric version, you can call a built-in function (yeah, this presumes that you come back here after reading the section on functions). In order to convert text to an integer, you use the function parseInt(). To convert text to a decimal number (a "float", as described before), use parseFloat(). Actually, these functions will take the first number they see in the text, such as 55 in "55apples". The original text will not change.
Perhaps the most common type of statement, and the one we've been using extensively, is the assignment statement; this assigns a value to a variable. In most of our examples, we have been declaring a variable simultaneously, though you don't have to. In this example, we change our mind:
The only important note here is that the equals is not quite like the equals you would see in algebra. You are not stating an equality. In fact, to disambiguate this, many languages use a different symbol, such as these:
Now we see an example which clearly demonstrates that we are not stating an equality:
Clearly, in algebra, this would be false. What happens here, like in any assignment statement, is that the right half is evaluated first, then that value is stuck into the variable on the left. The left can only have a single variable; i.e. the following is invalid:
When assigning a value to a variable ("setting a variable"), you will probably want to do some arithmetic, such as this:
Now for some more formalism. The arithmetic symbols shown before are called operators. There are other kinds of operators, such as && ! =, etc. Basically any symbol you see in a program is an operator. Each piece of data in the expression is called an operand (like 38, 5, 8, and 144 in the example).
You can also make several concatenations in one statement, and this is common. For example:
Let's go back to our earlier example: aNumber = aNumber + 1;. In this example, we set aNumber to be one more than whatever it already was. This is actually extremely common in programming. It is so common that there is a special syntax for it:
This statement alone is synonymous to our earlier assignment statement. This is where the language C++ gets its name; it was meant to be like the language C but better. This is also valid:
These ++ symbols can be called incrementors (actually the "[prefix or postfix] increment operator"). This is because the number is being increased by just one increment (the value 1). These symbols have slightly different behavior than our earlier example of aNumber = aNumber + 1;. In order to stay safe, you can avoid using them in larger expressions such as this:
What actually happens here is that the previous value of aNumber is used in the computation, and aNumber is incremented later. Weird! If you use the prefix operator - ++aNumber - then aNumber is incremented first and then the new value is used.
There are also decrement operators, such as --aNumber and aNumber--, and they work in complementary ways.
Finally, there are operators which simplify this type of statement in general: aNumber = aNumber + somethingElse;; observe:
And yes, the += also works for strings.
There are actually two ways to write comments. In the most common method, you start with two forward slashes, and the comment continues until the end of the line, like this:
You can also use a multi-line comment syntax, which begins with /* and ends with */, like this:
You can look at functions in a few different ways. If you have a math background, they are procedures which take inputs and produce outputs; in programming, this can also be true. They can also be containers of chunks of code, without taking inputs or outputs. Let's first use them in the mathematical way.
Consider the math function f(x) = x2. Basically, this takes the given number and produces its square. We can represent this pretty easily in programming:
We should be able to deconstruct this example and learn how functions work. So, on the first line, we define a function: we give it a name, and we accept some information in a variable. This variable, aThing, corresponds to x in our math example. Now consider the return statement. The return statement is the statement which declares the result of our function. As you can see, this takes the given number, multiplies it with itself, and uses that as the result of the function. This produced value ("return value") is caught by the code which "calls the function", demonstrated in those last few lines.
Parameters are the variables which hold the data given to functions. There may be any number of parameters in a function, not just one. For example:
Our function is called Force and its parameter names are mass and acceleration. These are now accessible within the function using those names.
Using our math example, you may think that functions are limited to quick, one-line expressions, similar to return x2 + 5y + 13;. This is not the case. You can have an arbitrary amount of code inside of a function. Example:
You can do anything you want inside of a function. They can be much longer and much more complicated than this, and they often are. When you finally use return, it will end the function and give the value following "return" to the function caller. If there is any code after a return statement (at least in our examples so far), it will not be reached.
In programming, the scope of a variable is the region of code in which the variable is valid. Outside of that scope, the variable is not defined and has no meaning. For example, consider these two functions:
No information is shared between these two functions. The variable userHeight is not usable in FunctionB, and likewise, userWeight is not usable in FunctionA. They could actually both have variables called userHeight and userWeight, and there would be no conflict or sharing of information. They would simply be oblivious to each other.
So what is the scope of a function parameter? A function parameter works exactly like a variable that is declared within a function, including scope.
It is possible and often useful to have a function which does not take parameters. This is where we may diverge a little from the concept of a function in pure mathematics. Sometimes, functions like this tell us something about the environment, and we call the functions in order to check on those environmental conditions. Examples:
We don't really need to give any parameters in these cases; we are simply retrieving or consuming information. In real life for these cases in particular, specifically with CurrentTime, we may actually give some parameters that specify how we want to format the time (like whether to use 12-hour or 24-hour notation).
In an even farther departure from math: you don't even have to return a value inside of a function. Some languages make a distinction in this case and call these functions procedures; most languages don't. Example:
So we don't need to take parameters, and we don't even need to return anything. We can just have a function with some lines of code inside, and that's it. In fact, this is pretty common, although functions usually take parameters. And there are actually benefits to making functions simply to contain, or "encapsulate", a chunk of code. The benefits are more in the realm of software design and how you choose to organize the structure of your program. For example, let's see the benefit of encapsulation:
The logic for computing BMI is only written in one place, which is more convenient than writing it out in each place, in terms of whatever variable names you have in each place (notice userWeight, weightOnRecord). It is also much easier to guarantee that the BMI calculation is correct if it is only written once; imagine if one of 100 occurrences of BMI calculation were incorrect, because you copied & pasted the BMI logic throughout your program and slightly adapted it each time. Function encapsulation is a tremendous benefit, and any time you see a problem that can be solved generically and then reused in multiple places, you should probably make it its own function.
Up to this point, we have had no variability in the logical path we take within each function. The data values may change, because they are in variables, after all, and variables can vary. But the steps that we take have not varied depending on the given information. We said that programs are like flow charts, after all, and flow charts represent different logical steps that you can take; e.g. "if the glass is not full yet, keep pouring; else stop pouring". There are programming structures we can use to capture this kind of variability, most notably the if-statement. Example:
This logic is actually a little incorrect, but it's a good basis for now.
So this is an if-statement. It's pretty simple. The expression inside the parenthesis has to have a value of true or false, so it cannot be something like x + 7 (even if it could, depending on the programming language, you probably shouldn't do it).
When you make a comparison for the expression within the parenthesis, such as our userAge > 18, you can use some new operators (remember arithmetic operators from before: symbols such as +, +=, etc). These are generally called logical operators or sometimes comparison operators.
A few of them are intuitive: < and > work pretty much exactly as you would expect (however, see next section). Some of them are not the syntax you would guess.
If you want to test for equality, you need to use a double equals sign, such as ==. If you use a single equals, it will try variable assignment. This is the case for most popular languages and is generally considered a regrettable design decision. You just have to know about it step around it.
If you want to test for a numeric range, such as userAge ≥ 21 (greater than or equal to), you will have to use a combination of symbols: >=. Similarly, there is <=.
If you want to negate an expression, you have a couple options. If you simply want to test whether a value is not equal to another, you can use !=, such as userAge != 8. Alternatively, you could surround the expression in parentheses and put a ! before it, such as !(userAge == 8) or !(userAge >= 21).
Comparisons have different meaning depending on the data type. If the data is an integer, such as userAge, checking if userAge > 18 will only become true at ages 19 and over. When conceptually we mean 18, such as 18 and 1 day, 18 and 3 months, etc., for integers, the next step is simply 19. So you probably mean userAge >= 18 or perhaps even userAge > 17.
You can also compare string data. If you say player1Name < player2Name, for example, this could make sense. This is comparing using an order that is approximately alphabetic (actually "lexicographical"; includes numbers and symbols in a certain order (can usually assume ASCII)).
There is actually another data type: the boolean type. One of these could also be called a "bool"; this is most common. This type of variable can hold the values true or false. Example:
We can also use expressions that evaluate to true or false. Example:
Since we can do that, we can actually use boolean variables directly in if-statement expressions:
This is similar to saying "userIsOfLegalAge == true", but that is actually redundant, so we can just do this. Likewise, you can say if (!userIsOfLegalAge).
If-statements can be far more complex than those we've seen. The structure is the same, but the boolean expression inside the parentheses may be much more complicated, like any math expression with several variables and operators.
You can say something like "if user age is greater than 18 and less than 25, [do this]". Let's see that example:
You can group simple true/false expressions in parentheses and then combine them. When you combine them, you can can use operators which effectively mean and/or. The and operator might literally be "and" in some languages, but it is usually a double ampersand: &&. Similarly, you could type "or" in some languages, but you most commonly use a double bar: || (typically shift + backslash). Example of an or expression:
Notice that this would not work with and, because a user's name cannot be two things at the same time. This is a common rookie mistake.
The and/or operators probably work how you would expect, but if you would like a formal introduction, look up "boolean logic" or "boolean algebra"; see Wikipedia.
As you can see, when you have multiple expressions, you can group them with parentheses. You can have sub-expressions and sub-sub-expressions if you want; there is no limit. Just keep stacking up the parentheses. If you don't use parentheses for expressions, you rely on the order of operations (remember PEMDAS). This is language-specific but you can generally assume it's the same across languages. However.. you probably should not rely on the order of operations. You should use parentheses to remove all ambiguity and separate your code cleanly so that it is readable, especially to other people. Omitting parentheses is generally considered annoying, perhaps offensive, and a give-away trait of the inexperienced.
You can also do this:
This is considered cleaner than our first example.
Similar to the if-else construct in the previous section, you can chain multiple conditions together, like this:
The if-statement structure, includig all forms of it, with else and else if, can be "nested" within another if-staetment. There is no limit to how deep your structure can go, and it is typical to see two- or three-deep structures. Example:
We are still missing one final piece of the majestic flow chart: repetition. You have probably seen flow charts which have a circular flow in them, such as "invite people in the room; if the room is not full yet, repeat". We must have an equivalent structure in programming in order to make useful and convenient programs. Enter the while loop.
The while loop is a structure which encloses an arbitrary section of code that executes repeatedly. Conceptual example:
As long as someCondition is true, those two lines will repeat. In this example, however, someCondition never changes, so we actually loop forever. This is practically never desirable, so we usually structure the loop so that the inside of the loop changes the loop condition, eventually breaking it.
A typical example for looping is to loop a certain number of times; say that you want to execute a given piece of code five times. You might do it like this:
Step through the code in your head. The variable loopCounter is incemented each time, and it eventually becomes 6, which, when put into loopCounter <= 5, makes the expression false. At that point, the code inside the loop is not executed.
So this may be seen as a generalization of most while loops:
What happens when the condition is false the first time? The code is not executed. For example, the code inside this loop never runs:
What if you want it to run at least once? This is sometimes useful. There is a variant form called a do..while loop which does this. Example:
Notice the semicolon at the end. So, this "something" code executes at least once, regardless of whether someCondition is ever true.
There are two simple statements, break and continue, which have special meaning in relation to loops. You may use them like this:
If you use continue, it skips the rest of the loop iteration (i.e. does not "do some more work" in the above example) and starts a new loop iteration. If you use break, it stops looping immediately.
Notice the semicolon at the end. So, this "something" code executes at least once, regardless of whether someCondition is ever true.
Not all loops are counting loops, but counting loops are probably the most common. So there is another kind of loop which is basically a rephrasing of the while loop that makes counting easier; it is the for loop. Example:
The for loop has four sections. Let's notate them generally and describe them.
They are as follows:
In 95% of cases, for loops look almost exactly like our first example. There are two typical differences and they are cosmetic. This is an exactly typical example:
The loop variable, or loop iterator, is usually called i. This is for a historical reason. The second difference is that the counter usually starts at zero; this necessitates that the condition become less-than in order to count the same number of times. This is just a very pervasive convention, though it comes in handy later (because it fits with other arbitrary conventions).
The statements break and continue are valid inside of for loops, as well.
A final note on loops.. You should probably not mess with the loop variable inside of the loop. Only read from it, do not modify it, unless you are both an expert and an awful person.
Like nested if-statements, you can also nest loops. You can nest any kind of loop — while, do..while, or for (you can nest practically any kind of structure within another, except for a function (in most languages)). For example,
As you might expect, the entire j loop executes for every iteration of the i loop.
The names of nested loop variales typically continue as j and k. Nested loops are somewhat uncommon and three-nested loops are rare.
If you have a for loop, why use a while loop? Well, for loops are fairly ideal for counting, and while loops are typically used for other situations.
There are perhaps two typical uses of while loops. In one case, you may just want to loop until a given computation is complete (passes a threshold), because it would be infeasible to calculate the number of iterations in advance and make it a for loop. For example:
In that case, you could deposit $10 every month, with 0.5% monthly interest, and the loop continues until you have a million dollars. To be extra useful, it computes how long it took to reach a million dollars.
In the second use case, you may loop an indeterminate number of times. This is often when you're asking for user input and the user keeps giving you incorrect input. There's no telling how many times that will take. If you ask for the user's age and he keeps giving you a string ("asdf"), it could go on forever. So a loop might look something like this:
You could also use a break to spice things up. For example:
This final structure is in most programming languages, though it is not extremely common in programs. It is a simplification of this type of construct:
If you simply have a bunch of equality checks on the same variable, you can structure them in a switch statement like this:
That's pretty much it; copy this example if you want to use it. It's just a more readable and perhaps more convenient syntax. You can have any number of statements in each case, before the break statement.
You can get started on your own custom web page, a web page provided alongside this document, or a popular online testing environment.
To refer to an external file, use the tag with a src attribute and with no body:
These are your most basic methods of output and debugging. With these, you can basically dump some text to the screen in one way or another.
If you are using Firebug, it has its own version of the console which has some extra convenience. If you are dumping arrays or objects to the console, it will give you a visual representation, which is extremely helpful.
You may also call the built-in function document.write, and this will write HTML to the page. It is rare to see this in any real site (there are more professional alternatives), so you should only use this while debugging or playing around. Example:
Finally, you can launch a pop-up message by calling the built-in function alert. This is also known as window.alert; they are two names for the same function. Try it:
This is bundled with the course materials
Many programmers have come before you. You can almost always find the answer to an introductory programming question with a little Googling; be sure to mention which programming language you're using in order to get more relevant results. The site Stack Overflow is specifically designed as a site for programming questions & answers, including many newbie questions. Your question has probably already been asked by somebody else, so try to find that before asking a duplicate question.
Now you know the basic building blocks of most programming languages. People have grown to use these tools in typical ways; here are some of them.
You know that boolean variables can store true or false. You can use these in some helpful ways.
You've seen that you can use a boolean variable in an if-statement; here are some refresher examples:
You may want to leverage this to simplify your if-statements and especially to save a true/false value for a later if-statement or a repeated one. First, for simplifying if-statements:
By giving a name to the expression, you can make the if-statement more readable. You could also have done that with a comment:
So that is more of your choice, one way or the other (but please do one of them). Code readability is an excellent goal in programming and it is one that is only recently becoming appropriately emphasized.
Aside from readability, is it ever useful to save an expression like that in a boolean? Yes. Here is one typical example:
In this example, you could have written the userAge and userGender expression each time, but this example is more readable, easier to verify, and easier to maintain. Copied & pasted code is one of the main sources of errors; you might forget to change one little part after pasting, or you may forget to update all of the copied & pasted occurrences of the expression if you want to change it. With setting one boolean variable, you can change the meaning of that variable in one step (add some criteria about the person's income?) and it is effectively updated everywhere.
Function parameters will often be a boolaen type. It's an easy way to express a preference; it's like asking "Yes"/"No". For example:
We have seen so far that you can have variable within a function and it is valid only for its function. That is the variable's scope. Now we will see that you can also have variables outside of functions. Those variables are valid everywhere and thus they are called global variables. The regular variables you've seen before are called local variables. Example:
The variables userName and userAge are accessible everywhere in the program, and they may also be modified from everyhwere in the program.
So, in our earlier example, FunctionA() reads from the userName and userAge variables, and FunctionB() writes to userAge. (Perhaps elsewhere, userName is defined.) So does FunctionA() read the changes made by FunctionB()? Well, it depends. It depends on the order in which they were called. If FunctionB(), the producer, is called before FunctionA(), the consumer, then yes; else FunctionA() will see the original values for those variables.
Complications like these make global variables somewhat more dangerous than local variables, and many or most professional programmers try to avoid global variables as much as possible due to reasons like this, especially within the context of an already-complex program (global variables are probably fine for your small, educational programs). A way to avoid global variables in general is to pass the information with all the function calls instead.
Actually, you can have any code in global scope, not just variable declarations. You can do computation, ask the user for input, write output, etc. And after all, how do you think these functions are called? Example:
For better or worse, we have an easy way to persist some information between function calls. This can allow us to have an arrangement like this:
The title of this section refers to train-track semaphores
What if you name a local variable the same thing as a global variable? Well, in most languages, you can do that. And then you would begin using the local one; the global one would probably become inaccessible from within that function. It depends if the language gives you a way to refer to the global one explicitly (something conceptually like global.userName). In any case, whether you can do it or not, you probably shouldn't. It would be considered poor style, since this makes the program less readable and less clear; it also increases the general risk of screwing something up.
The rest of them are actually functions, such as this:
There are also functions for searching within the string:
An important note here is that the numbers start counting at zero. The "H" is at index zero.
There are several more functions, and you can find references online, such as W3Schools; the functions are called "methods" if they stem from a variable such as the string. The one important thing to remember about these string functions is that they do not modify the original string. Note how we had to make a copy of the string to capture the uppercase version. If you actually want to convert the string to uppercase, you must do something like this:
Arrays are collections of variables. More specifically, an array is a numbered sequence of variables, such as this:
You actually create arrays like this:
If you refer to the variable as arrayThree[someNumber], even if someNumber is a variable, it refers to that item in the list, at position (someNumber + 1), in terms of natural numbers and counting. If you refer to the variable without the brackets, such as just arrayThree, you refer to the whole array. You can make two variables refer to the same array in this way:
In this case, actually, these two variables now refer to the same array. So you would have to think about this kind of thing:
This kind of behavior is generally called reference semantics; i.e. the variables in this case refer to the same piece of information. This has not been true of any variables we've seen before, but we will see this again. (Actually, it's true of strings, but it has no effect except for using computing resources more efficiently.)
And just like before, you can find a reference on W3Schools. There are five functions which are particularly useful:
Arrays and for loops are fast friends. Using a for loop, you can step over all of the elements of an array and then perhaps dump them out or manipulate them all:
Like arrays, objects are collections of variables, except they are not organized in a list. They are just in a bag, and each sub-variable has its own name. For example:
Similar to arrays, you can also define an object and give it some values in the same line of code:
These sub-variables, such as "aNumber" and "favoriteShape", are actually called properties, or fields, rather than sub-variables.
Just like arrays, objects have reference semantics, meaning that if you set one variable equal to another variable which is an object, they both actually point to the same data. And like arrays, it is often useful to pass around the entire object:
As we've seen so far, you can access an object's properties like this:
But you can also access them like this:
Notice that we're using quotes here and we're actually buliding strings that will be used as property names. And wherever we have a string, we can also use a variable. This can allow for some cool things.
In the examples so far, we needed to know the property names in advance, but now we don't need them if we are doing batch operations on the object.
An object can hold anything - including an array or even another object. (An array can also hold anything, by the way.) So you may end up with an object which is actually a multi-layer structure of information, such as this:
Because of this, objects might be helpful ways to store natural phenomenon or structural information.
Using a variadic function is easy, though defining a variadic function takes some work.
In every function, the variable arguments is automatically defined. This is the array of values given for the function parameters.
Sidetrack in programming-language terminology: the list of function parameters' variables and their names is actually the list of parameters. The list of values given when the function is called is the list of arguments. For example:
In this snippet, name, age, and height are the parameters, and "John", 18, and 68 are the arguments.
So, there's an arguments array. That means you can do this:
The most basic use of variadic functions is declaring very few parameters (or no parameters) and accepting more arguments than the number of parameters you have declared. To do this, you just use the arguments array, really. This section will have examples of some useful special cases, though.
In this first example, we declare no parameters:
In this second example, we declare some parameters and leave the rest to be variadic:
A more difficult problem is when you want to make some parameters optional. For example, you want to make a function like this:
You would like to make some of those parameters optional. How do you do it? There are a few different ways to do this, but let's see one example. You can pretty much just copy this pattern; hopefully you also take a good look at it and it makes sense to you:
Note that if the function caller doesn't give those extra arguments, their corresponding variables (e.g. bbb) will remain undefined in the function, which is a little strange. So you have to declare them with var. Now let's see a version of this which is actually slightly faster because it uses fewer comparisons. This wouldn't really be noticeable in most cases but might be noticeable if you loop and do this a thousand times.
Why does this use fewer comparisons? It has four if-statements, after all. Well, they are in the else-if format. If the first if-statement is true, it will not bother checking all of the rest; if the second one is true, it will not bother checking all the ones subsequent; etc.
Fairly often, you will see an official documentation page for a varaidic function. These may be notated with explicit phrases like "Optional" next to the parameters. However, there is a shorthand which is conventional for denoting optional parameters: a set of square brackets is placed around the parameter(s). For example:
If a system is modular, it has interchangeable parts. A good example is a vacuum cleaner and its attachments. A vacuum cleaner can have any kind of attachment on the hose: a brush, a horizontal bar, a triangular head, etc., and the vacuum does not know or care any details of the attachment. You could even upgrade the vacuum and the attachments don't need to know or care that anything has changed. They meet in the middle, using a common interface (a cylindrical tube), and they require very few specifics of each other in order to function.
Software systems can also be modular, and in fact, this kind of interchangeability is one of the most consistently desirable goals in software design. A more formal term for this mutual lack of dependency is decoupling, which is also seen in engineering.
Let's say you want to take an array of persons' names and transform them somehow: let's say that right now, you want to convert them to uppercase. We'll start with a program like this:
We have two nice functions, and the ConvertAllStrings() function is decent - it performs a useful task - but it is tightly coupled with the ConvertAStringToUppercase() function. Put another way: the ConvertAllStrings() function only knows how to transform strings in one way (to uppercase), because it uses ConvertAStringToUppercase() (which may also be seen as a dependency on that second function). What if we could make ConvertAllStrings() a more general-purpose function: one that knows how to iterate over an array and change each of its elements according to any given transformation, not just convert to uppercase?
We can do this, in fact. Let's see the next step:
In this example, we tell ConvertAllStrings() which function to call. It no longer has any explicit mention of uppercase strings. Our function has a parameter which it uses as a function (whichFunctionToCall), so in that sense, the function to be called becomes a variable like any other variable. Now, you can choose any number of transformations with a minimal change of code and no change to ConvertAllStrings():
You can also make a new function on the fly and use it instead of specifying a function name. For example:
These kinds of functions are called anonymous functions. You may notice that the declaration is exactly like a regular function except that the name is missing.
You can use an anonymous function anywhere a function is expected, which is typically in the case of a function being expected as an argument to another function, like these examples. It may be cleaner or easier to do this than to have to declare a function and think of a name for every one.
To further expand on this subject.. the following two snippets of code have identical effect:
What's the benefit of making an anonymous function, again? One benefit may be convenience. Another benefit is this: the ability to tie in outside variables from the immediately surrounding context. This is an advanced topic, especially if you consider all of its implications, but the first examples are not too bad; try to understand them.
In the snippet above, we have two examples of use of anonymous functions. In both cases, we capture some information from the immediately surrounding context, such as the variable threshold, and incorporate it into the anonymous function. So we could even take this variable from user input (e.g. "Enter the minimum string length you want") - all while maintaining the modularity of functional programming. Pretty neat stuff.
There is certainly more you can do with closures and you may run into strange problems during your experimentation. However, other people have run into the same problems. Ask your question on Google or Stack Overflow and you will probably get your answer.