Basic JavaScript concepts

There are a few concepts in JavaScript that are often misunderstood or only somewhat comprehended. These include closures, scope, and context.

I found a very good YouTube video-series by Will Stern at LearnCode.academy which describes and explains these concepts very well. The video series is called “What Makes Javascript Weird…and AWESOME“.

Will goes through the following concepts:

  • First class functions
  • Event-driven environment
  • Closures
  • Scope
  • Context

I will give you a quick run-through here:

First class functions

There are a few different ways to define functions in JS (which I will be showing in an upcoming post), but the most basic one is to define a function in the following way:

function myFunctionName(agument1, argument2) {

    // do something

}

argument1 and argument2 are variables that are passed to the function that the function can then manipulate as it wishes.

Functions may also be passed as arguments since a function is in fact, to JavsScript, a variable in itself.

function myFunctionName(agument1, argument2, callbackFunction) {

    // do something with argument1 and argument2

    callbackFunction();

};

function callbackFunction() {

     // do something else

};

Event-driven environment

JavaScript uses an event driven environment. This means that while other programming languages execute their script when the page loads and is then for all intents and purposes “dead” until the page is reloaded, JS is kept in memory and remembers and listens to events that are defined in the code and will execute that code when the specific event is fired.

With jQuery we can easily attach a click event to a button and make a chunk of script execute when the button is clicked.

$("#myButton").on("click", function() {

    console.log("I am clicked");

});

Note that the function defined in the click event is a function that is passed to the on click event in the same way that we defined a callback function in the previous section. It can also be written as:

function handleClick() {

    console.log("I am clicked");

};

$("#myButton").on("click", handleClick);

Closures

The definition of a closure is something that retains state and scope after it executes.

In our previous example we said that script is “dead” once it has run, however, in a closure the script is still “alive” and can be reached and reused later on. For example, the variable clickText in the following example is still accessible and can be modified after it has run the first time, because it is in a closure.

var clickText = "I am clicked";

$("#myButton").on("click", function(){

    console.log(clickText);
    clickText = "I have been clicked once";
    console.log(clickText);

});

In the example we can see that the clickText variable being modified. This is because JS remembers that the variable text may be used in the click event so it retains its state and the scope that it is in.

Scope

Scope means variable access and is the container area that a variable can be used within because it has been declared in such a way that the current code can access it.

Child functions, for example, have access to its parent’s variables since they are in the same scope. On the other hand, parent functions do not have access to the variables of a child function since those variables only exist within the scope of that function.

Other examples of scoped variables are those which are defined inside for loops, while loops, if statements, and other such blocks of code.

var a = 1;

function foo () {

    var b = 2;
    console.log(a); // this will return 1
    console.log(b); // this will return 2

    var a = 3;
    console.log(a); // this will return 3

}

foo()

console.log(a); // this will return 1
console.log(b); // this will return "undefined"

As you can see, the variable a outside of the scope of the function foo will not be modified in this case since the variable a declared inside the scope of foo is a new variable that is only accessible inside of that function. Also variable b will be undefined outside of the function foo since the parent scope does not have access to it.

Context

Context is the value of this.

This is commonly used to access the current object and its methods, variables, and functions. But it can be a little bit tricky to keep track of exactly what it refers to at any given time.

In the example below you will see how this varies depending on how the function is accessed.

console.log(this) // logs window

function foo() {

    console.log(this); // still logs window

}

foo();

    var myObject = {

        bar: function() {
        console.log(this); // this will log Object { bar: function }

    }

}

myObject.bar();

In the last case where bar logged the object (which is the variable myObject) is because that is the context that bar exists in. The two examples above it both exist in the context of window.

If you want this to be something different, window for example, you must bind it to that context.

myObject.bar.bind(window);

Bind does not execute the function, to make it do so, create a function for it:

var myBoundObject = myObject.bar.bind(window);

myBoundObject(); // this will now log window

Leave a Reply

Your email address will not be published. Required fields are marked *