JavaScript concepts

I’ve been spending some time delving into JavaScript to get a better understanding of the language as I’m finding myself using it more and more. This is a summary of some of the concepts and fundamentals I wanted to jot down for future reference.

Objects and this

One key feature of JS objects is that for functions within the object, the this keyword refers to the object instead of the window. For clarity, it is still common to assign another variable, such as self to this in order to avoid confusion.

var c = {

    name: 'The c object',
    log: function() {

        var self = this;

        self.name = 'updated c object'
        console.log(self);

        var setname = function(newanme) {
            self.name = newanme;
        }

        setname('updated again');
        console.log(self);
    }

}

Function Declarations vs Function Expressions

A function declaration defines a named function with no variable assignment. Function declarations are hoisted at runtime.

function greeting() {
    console.log('Hello');
}

A function expression allows functions to be assigned to variables, be created without a name (anonymous functions) and be ran immediately after runtime (these are called Immediately Invoked Function Expressions, or IIFEs).

var g = function() {
    return("Hello");
}

Notice how the above function is anonymous, that is, it has no name. In this case, the variable g holds the function, and it can be executed through g();

Functions can be invoked immediately, like so.

var g = function() {
    return("Hello");
}();

In this case, the g variable would hold a string as the function is immediately executed.

The most common syntax for creating IIFEs is to encapsulate the function in () brackets.

(function(name) {
    return("Hello " + name);
}('John'));

Closures

In JavaScript, functions are first class objects, that is they can have properties assigned, be passed to other functions as parameters, can be assigned to variables, can be returned from other functions. A closure is a functional programming concept which allows a function to have access to variables outside of it’s execution context.

var name = "John"
function greeting() {
    console.log("Hello " + name);
}
greeting()