JavaScript Fundamentals #2

Today I watched a bit more of JavaScript: Understanding the Weird Parts on Udemy. I learned a lot more about functions than I had known previously and it is actually really useful.

First of all, it is important to note that functions are objects. This means that functions can be treated as objects and can even hold additional values besides the invocable code.

var greet = function() { console.log("Hi"); }
greet.value = "hi";
console.log(greet.value); // outputs "hi"
greet(); // outputs "Hi"

These are called in same way!

function greet() {...}
var greet = function() {...}
greet();

The ‘this’ keyword usually refers to the window object in the global execution context, but when we have

var someObject = {
    description: 'This is an object',
    act: function() {
        console.log(this); // will output someObject instead of window!
    }
}
someObject.act();

the ‘this’ keyword inside the function will output someObject instead of the window object. Pretty nifty!

However, say we have the same code, but inside the act function we do something different.

var someObject = {
    description: 'This is an object',
    act: function() {
        function someFunction() {
            console.log(this);
        }
        someFunction(); // This will log the window object!
        console.log(this); // will output someObject instead of window!
    }
}
someObject.act();

In this example, someFunction() inside of the act() function will log the window object instead of the execution context we expect, which I expect to be the act function. Just some odd behavior I learned from the lecture.

Furthermore, I learned that you don’t have to pass all arguments to a function that has declared necessary arguments, which is different than how Java is made.

In this Java function example, we need to pass in arg1, arg2 and arg3 in order to use the function without any runtime or compile time errors.

public void someFunction(int arg1, int arg2, int arg3) {...}

In this JavaScript function example, we don’t have to pass in all the arguments! Instead, JavaScript will take in as many arguments that you passed in and will use the first passed argument as the first argument in the function and so on until there are no more passed arguments. JavaScript dynamically typed feature helps with this, since we can treat a variable as undefined.

function someFunction(arg1, arg2, arg3) {...}

That’s all I have for now! Hope this helps.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s