Categoryscope

Scope in Go

When we talk about scope in any programming language, we are referring to how the code can access variables. Scope defines where a variable can be accessed based on how it is declared. Scope in Go is fairly simplistic. In this post, we will be talking about scope in Go.

Go has three specific types of variables: local variables, global variables and formal parameters. First of all, local variables are found inside of a block or function. Also, global variables are found outside of all functions. Finally, formal parameters are the variables in function definitions.

scope

Local Variables

Local variables are the most common type in Go. They can only be used by the statements that are in the block of code in which they were made. This is to say that local variables are not accessible by functions outside of their own. Look at the example below.

These variables are bound to the main function. They can’t be accessed by a function or block of code outside of the main function.

Global Variables

Global variables are typically defined outside of all functions and at the top of the program. This style of defining a variable at the top is idiomatic in Go. Global variables have a lifetime that last as long as the program runs. They also can be accessed by any function in the program that follows their declaration.

In this program, both of the functions have access to our global variable. This has its advantages and disadvantages. Consequently, any function has access to this variable which means any function can change this variable.

scopeFormal Function Parameters

Finally, we have formal parameters. These variables are treated like local variables and they gain preference over global variables. Therefore, if the global variable shares the name of a formal function parameter the formal parameter will be used. So, Let us look at an example of this.

In this somewhat nonsensical program, we have three variables that share the name, g. One is a global variable, one is a local variable and the other is a formal parameter. We are also calling the references for these variables to show that they are different. This reference notation is something we will look at closer in our next post. For now, all you need to know is that the three values are different from one another. Furthermore, each time we print the reference to g out, we are calling a different block of memory. 

Conclusion

In this post, we looked at scope in Go. We looked at local variables, global variables and formal functional parameters in Go. We touched briefly on pointers and references in this post as well. In our next posts, we will be going over Pointers and References in Go. 

Self-Invoking and Anonymous Functions in JavaScript

Functions are used in many different areas of JavaScript. Functions in JavaScript are a powerful way of freezing code for further use. Thus far, we used different functions to define object constructors and object behavior. In this post, we are going to look at some of the other ways that we can take advantage of functions in JavaScript.

Anonymous Functions in JavaScript

anonymous functionIn JavaScript, a typical function declaration utilizes the function keyword followed by the name of the function. We name our functions when we want to invoke them multiple different times in a piece of code. Sometimes, we want to be able to pass a function directly to another function as an argument. We were actually doing something like this when we were defining our getter and setter functions in our last post. The get: and set: keywords are both function shortcuts.

Most of the functions we’ve been writing inside of objects are called anonymous functions. Anonymous functions are functions that are not defined with a name. Typically, these functions are used for one of three main reasons.

The first way they are used is for direct variable definitions. This style of anonymous function is the most like a normal function declaration in that it is bound to a variable name. It can be invoked by calling that variable as an execution (with parenthesis). This is the type of anonymous function you will most commonly see inside of objects and constructors as well.

These are not the most realistic examples but they work for our purposes. These shaky examples just simply show that you can substitute a return value for a variable declaration in most cases. The second example displays a concept called side-effecting which we will talk about at length in a future post (the console.log() is the side-effect).

Callback Functions

Another common way that anonymous functions are used in JavaScript is as arguments for other functions.

callback anonymous functionsThe setTimeout() function is a very good example for this type of use. The first parameter that we pass to it is a function we want to run. The second parameter is the amount of milliseconds that we want to pass before this function runs. In this example, we’ve specified 3 secs or 3000 milliseconds before this anonymous function runs. You will see this type of anonymous function used many times when working with web applications. Typically, we call these functions callback functions.

Before we get to the last most common method of using anonymous functions, we need to define self-invoking functions.

Self-Invoking Functions

A self-invoking function is actually an anonymous function itself. A self-invoking function automatically runs on its creation and can only be run once. Here is the general format for this type of function.

self-invoking functionsFunctions run immediately in JavaScript when you place a set of parathesis after their names. This is an important thing to remember because in JavaScript you only put semicolons after execution statements. You may have noticed that after a function declaration you don’t put a semicolon. This is because the code is being stored for later. With self-invoking functions, however, we are not storing any code for later use. We are running the function right then and there.

The main reason to use a self-invoking function is for data privacy. Self-invoking functions are primarily used to create what is called a closure. A closure is a method of creating private variables inside of a function block. Closures can be used to create variables that act like the block scoped variables created by let as well. Closures are our last main use case for anonymous functions.

Closures

In JavaScript, functions have access to global variables and to variables defined inside of them. This can be a problem, for example, in web development, the global variables belong to the window object. Any script running on the page can actually access and manipulate any of these global variables. Look at this classic example.

With these examples, we can’t increment the count variable past one because every time we call the functions, we reset the count variable to zero. If we use a closure, however, this problem is easily solved.

closure-introIn this example, we set the add variable to the return value of a self-invoking function. This means that the outer function only runs one time, which sets counter to zero. The inner function works like a normal anonymous function. After the outer function runs from the declaration, when we call add(), only the inner function runs. In this example, the scope of counter is only inside of the self-invoking function and the add function. This means that after the self-invoking function runs, the add function is the only function that can touch it.

Closing

In this post, we took a look at the primary use cases for anonymous functions, for variable definitions, for callback functions and for creating closures. We also looked at self-invoking functions and how JavaScript scope can sometimes work against us.

In our next post, we will start to look at classes in JavaScript. As always, feel free to leave a comment if you thought we left anything out or if you need more clarification.

Variable Scope in JavaScript

In our last two posts, we started looking at functions and objects in JavaScript. Both functions and objects make use of variables and because of this, we must discuss the concept of scope in JavaScript before going further. In fact, objects and functions themselves are also subject to scope in JavaScript because they are also treated as variables.  Scope is a concept that you will see in many different programming languages and it is much more powerful than it seems at first.

So, what exactly is scope and how does scope in JavaScript work specifically? Scope refers to the set of variables, objects, and functions that you have access to at a given area of a program. In JavaScript, where you define a variable is extremely important because it determines the “visibility” of that variable in different parts of the code. In many other languages, you have access to different keywords that let you change the scope of a variable but this is not the case in JavaScript.

Scope in ECMAScript

You have two main forms of scope in JavaScript (pre-ES6); global scope and local scope. The upcoming iteration of JavaScript, ECMAScript 6 (ES6), also features the ability to bind a variable to a block; this is called block scope. To better demonstrate what scope is, take a look at the code below in our JavaScript console.

As you can see, we have defined the variable x on three separate occasions in this code. Our first declaration is what is called a global declaration. This means that all of the code has access to this variable. The variables x that are defined inside of each of the functions are local variables. These variables can only be accessed by the functions themselves. Notice that the function, example_1 also uses a local scope. The x referred to inside of example_1 is the argument passed into example_1.

scope_chainingIn a way, scope refers to the lifetime of variables; that is, how long variables stay in memory. In the case of globally scoped variables, the variables will stay in the ram until you close the program (or browser window).  With locally scoped variables, the variable only lasts until the function it’s scoped to is executing. Let us take a look at this next example to see some of the quirkiness of the scope in JavaScript.

It is worth noting that using a return statement can change the scope of a variable in an artificial way. If you return a variable from a function then it is still visible in the parent code body.  In this way, you are extending the lifetime of a locally scoped variable by passing it into it’s parent.

Strange Scoping

What do you think will happen when we run the strange function? common sense tells us that the function will print 1 then 30 to the console, but this is not actually what happens. We see undefined, then only one print declaration of 30 and then another undefined. The reason for this is that JavaScript always moves the variable declaration to the top of the scope. The function strange should actually look something like this.

strange_2 also gives us the same output as strange did. If you define a variable but do not give it a value and then pass it to the console.log() function, you will see undefined print to the console then get a return value of undefined as well. This is essentially what is happening with strange and strange_2. The variable declaration of x inside of the function becomes locally scoped to the function and it is passed undefined into the first console.log(x) statement. x then receives the value of 30 and it is printed to the console.

The Let Keyword

es6-letBefore we wrap this up, let us take a small peak at block scope from ES6. ES6 introduces many different keywords to JavaScript, one of which is the let keyword. The let keyword works like a var declaration but it is specifically made for block scoping.  Here is an example of block scoping using a modified version of the example_3 function from before.

The non_block function suffers from a similar problem to our strange function in that the var x inside of it is pushed to the top of the scope. This causes the first console.log(x) statement to print undefined and then print "block" twice. In our block_scope function, the let keyword does not become a locally scoped variable because it’s bound to the if statement instead of the function. This is why we get "global" "block" "global" as our print outs.

Like global and local variables, a block scoped variable only “lives” in the code until the code-block it is scoped to finishes running. In this case, the if statement finishes running and the let x binding dies before the last console.log(x) statement is run.

Conclusion

In this post, we looked at scope in JavaScript. We saw examples of local scope, global scope and block scope. We introduced ES6’s let keyword and looked at some of the strange examples that came from pre-ES6 scoping rules. In our next post, we will continue our journey and expand upon what we already know of objects and functions.