Learning JavaScript part 4 Objects part 2

Note: By mistake I set publish date to November, silly me =(


Function is usually a named block of code which performs a task or calculates a value and which is declared by keyword function . Special type of function without return value is called a procedure. Function defined inside an object is usually referred as a method.

Function is declared by keyword function which is followed by

  • function’s name
  • list of arguments in parentheses and separated by ‘,’ (comma)
  • statement(s) in curly brackets

In Example 1 we pass an argument number  and the we use that argument as a return value through keyword return .

Functions, usually procedures, can modify variables inside it’s scope.

At this point I’ll try to explain what is the scope. It is a space in code where certain variable exists. In Example 2 the variable  a  exists globally compared to

locally  and  b  which are defined only inside the function test and can’t be accessed from outside the function.

In Example 2 we can also see usage of a function on line 6. Definition of the function on line 2 does nothing on its own. Probably the best analogy for function from “real” world is a hammer in a drawer. We have it there hidden but until we use it it does nothing.

When we are at it I should mention a term closures which is a powerful feature of JavaScript. It means that you can nest functions and the inner function has access to all variables in the outer function. But it is not vice versa, outer function cannot access inner function’s variables.

In this simple case we called inner function to return variable which is defined in outer function. Closures can be more powerful than as shown in Example 4:

In last two examples I used what is called an anonymous function. This type of function doesn’t have a name and can be accessed only locally.

When we defined local variable with the same name as some global variable then we won’t be able to access the global one and we will only work with the local one. In other languages there is an easy way but in JavaScript there is a major pitfall when it comes to keyword this . Because it doesn’t depend on where it is defined but rather where the function is called. Therefore following Example may or may not always work:

 Argument object

An interesting feature is an array-like object arguments . It can be iterated through in a for cycle but it doesn’t have all array manipulation methods.

 Function object

Function object is a special JavaScript object which specifies a string of code to be compiled as a function.

Predefined function

  • eval
    • evaluates a string of JavaScript code
  • isFinite
    • returns false if an argument is not a number (NaN), positive or negative infinity
  • isNan
    • tests if argument is not a number
  • parseInt, parseFloat
    • parses a number out of string until first non-numerical character except for ‘.’ for float is found
    • if a first character in string is a letter it returns NaN value


Today we’ve looked at functions. We’ve learned about scope and closures. Next time we’ll start finally defining our own objects.


An interesting post about closures.

Learning JavaScript part 3 Objects part 1

Note: As you can see this post is part 1 of a sub-series about objects and object model in JavaScript.

Even though I used object-oriented programming (OOP) paradigm countless times in the past JavaScript’s object model is at the moment a bit unclear. But before we dive into creating our own objects let’s learn the basics with predefined ones.

Note: Some parts will be explained later because they might be confusing at a time.


In general arrays are indexed and/or named sets of values usually of one data type. I use this definition because that is what I am used to from writing code in C-like languages. But JavaScript unlike Java is weak typed language and doesn’t have an explicit arrays data type.

Also unlike Java in JavaScript an array is a predefined object which can be created in three different ways:

First two cases use directly the Array object and third uses simple enumeration of elements inside square brackets.

As in other languages it is possible to create uninitialized, elements have default values, array of specified length:

JavaScript uses numbers for indexing arrays and first element has index 0 (zero).

In Example 4 we create a new array and begin to populate it with elements starting at position 0.  length  is a property of object Array. In next example we’ll see similar code:

Example 5 produces different result. It is because  length ‘s value is implicitly defined as highest index plus one. But as we’ve seen in Example 2 it can be set to specific value.

Another thing I’d like to mention about populating arrays is that one can assign elements of various data types to different positions in the array:

I advise against it.[ref]Remember that you’ll have to write more code which detects types of values and comments explaining structure of said array. Respect that coder should write readable code for other not just for themself.[/ref] When I need to store different data types together I rather use JSON or objects defined by myself.

Array methods

JavaScript provides several handy methods I didn’t know about and a lot I used before. Here is a list of those I have found interesting:

  • concat()
    • turns two arrays into one


  • join(deliminator = “,”)
    • joins all elements into a string separated by deliminator


  • push() and pop()
    • work as when one works with stack
  • sort()
    • sorts array with default algorithm or user defined algorithm pass as a callback function


  • every(callback[ref]callback is a function which you can call when ever you execute some other function or method.[/ref]) and some(callback)
    • I haven’t used these functions yet but they’ll come handy one day. They return true if all/at least one gives true value from call back.

At this point I would like to go to loops for a bit. There are two forms of for  loop


Iterates a variable over all properties in an object

This loop is not recommended for iteration over the Array object because we assign variable a name of the property and then we have to access it again inside the loop.

for each…in

This loop is better suited for iteration over arrays because it iterates over property value and not names.

I am mentioning these loops here because Array object has method  forEach(callback)  which is a part of JavaScript’s functional programming traits. And I didn’t want it far away from  for each...in .


I left out multidimensional arrays simply because it is an array of arrays. That’s the only reason. In next part we’ll dig into  Function  object.

Learning JavaScript part 2

Computers in the past were used mainly for calculations. But as demands grew programmers needed to use more sophisticated tools to control execution flow. First we’ll take a look control structures and in second half at loops.

Control structures


The simplest control structure is if (exp) . This statement will allow execution of first statement or group of statements in curly brackets (braces) if expression exp is  true .

More complex form of if  statement is combination of if...else which will execute statement(s) depending on expression behind if .

It is also possible to put several if  statements in a cascade:


When I was beginning to learn programming at high school, we learned Pascal then, I feared this statement because it never worked as I needed. Therefore my first programs were made using cascades of if s. Not the most elegant way of coding but brute force works until something breaks. With heavy usage of if cascades it is usually readability of mine/yours/someone else’ code.

Switch is a simple way how to execute statements according to expression in the switch  statement.

In the example 4 we have rewritten if  cascade from Example 3 to a switch  statement. We have to use default  case for the moment when expression gives us different value than 1 or 2. It’s a matter of safety.[ref]Do no harm! Unless you are programming a missile or creating new replicators[/ref]

break  statement is not mandatory in this control structure. But you’ll have to use it when you want to execute only certain set of statement per case .

break  statement is used also in loops.


for loop

Loops in general are used when we need to repeat some action more than once in a row. There are two types of loops. Ones where we know how many iterations will be done and ones without a known number of iterations. for  loop belongs to the former category. Most common syntax for this loop is following:

Parameters for the for  loop are initial state, exit condition (i. e. when the loop can be executed) and what should be done after each iteration.

 while loop

This loop belongs to the latter group where we know only exit condition. Therefore it has much simpler syntax compared to for  loop.

Certain modification to a  while  loop is  do ... while  . The only different except the keyword do  is that the latter loop will execute at least once.

Warning: Some languages, let’s not mention Pascal, work strangle with this loop. Logic states that this will work as log as exp is true. But in Pascal it works as long as !exp is true.

Extra: while  loop can be rewritten as a for  loop:

break statement

This statement is used whenever programmer needs to terminate switch statement or any loop immediately.

 continue statement

continue  statement is from my point of view an extension of break  statement because it breaks current iteration and restarts whole loop.

Example how it works:


In this post we have seen control structures  if ... else and  switch . We’ve talked about  for  and  while  loops. Those two are not the only loops you can use but  for ... in  and  for ... each  are more complicated and I think they should be explained in the post about arrays which is by coincidence next post.

Learning JavaScript part 1


I first met JavaScript more than ten years ago. I didn’t see its purpose except for simple effects, such as hiding elements, showing current time or number of visitors. The best things, from my point of view, were made in Flash. And let’s not forget that then JavaScript was recommended to be blocked. Continue reading “Learning JavaScript part 1”