Code Blocks, Functions, and Scope - JAVASCRIPT: A Beginner’s Guide to Learning the Basics of JavaScript Programming (2015)

JAVASCRIPT: A Beginner’s Guide to Learning the Basics of JavaScript Programming (2015)

Chapter 7. Code Blocks, Functions, and Scope

If sentences are like statements, what are paragraphs like? Yes, in programming, you might also have to create some sort of paragraph. They are called code blocks.

Code blocks are multiple statements that are grouped together. They are not necessarily a term most developers use, but for easier understanding of the next topics, groups of statements will be called code blocks. Also, please do not confuse this with the IDE Code Blocks.

In most cases, you will need to separate certain statements and group them according to the goal that you want to achieve. In programming, it is usually done by creating code blocks, and making them functions.

Functions

Functions are grouped lines of codes that do not immediately run when the browser parses them. Unlike regular lines of codes and conditional statements, the statements within a function are executed when the function is invoked.

They are especially useful in decluttering your source code and making it more readable. Also, its primary use is to organize your code and minimize the lines of codes you need to type, especially if you need to execute the code block multiple times. After all, functions can be invoked as many times as you want.

Here is an example of a JavaScript function:

> function exampleFunction() {

alert("This is a function.");

}

< undefined

> _

Note: If you are going to type this on the Developer Console, you can press Shift + Enter to create a line break without submitting or entering the code in the console.

Even if you put this block of code in the topmost level of JavaScript script, it will not run. The browser will just record its existence, and it will be executed when an invocation of this function occur.

Note: Unlike variables, you cannot change the code block or value within the function at runtime through your code (although with the use of DOM, it can be overwritten). However, it is possible to change a function’s statements through the Developer Console — variables included.

To invoke a function, you must call it by “mentioning its identifier.” For example:

> exampleFunction();

< undefined

> _

Once invoked, all the statements within the function will be executed by the browser. In the example’s case, the alert box will appear.

Also, do note that functions can also invoke other functions within their code blocks. Another thing worth mentioning is that a function can invoke itself; however, you will encounter a maximum call stack size error. That error occurs since the browser will be infinitely looping again and again the invocation process, in simple terms. For example:

> function supahLoop() {

supahLoop();

}

< undefined

> supahLoop()

xu Uncaught RangeError: Maximum call stack size exceeded (…)

> _

Note: When invoking a function, make sure that you include the parentheses. Without them, some browsers may not invoke the function. In Developer’s Console, submitting the function’s name and not including the parentheses will only result to the console showing the contents of the function.

Scope

Scope is the accessibility of your variables. Depending on the location where you declared them or how you use them, their scopes changes.

For example, a variable that was declared inside a function will not be available to codes outside functions. Here is what this is all about:

> function exampleFunction() {

var x = 2;

}

< undefined

> exampleFunction()

< undefined

> alert(x)

xu Uncaught ReferenceError: x is not defined (…)

> _

In this case, it seems that writing a function, putting a variable declaration inside it, and invoking the function will make the variable within it available outside the code block. However, due to scoping, it will not work.

Variables declared inside a function will only be available inside that function. For example:

> function exampleFunction() {

var x = 2;

alert(x);

}

< undefined

> _

When you write the previous sequence of statements, the alert box will be executed and the value of variable x will appear on it.

What will happen if the variable was declared outside the function? Can the function use it? Here is an example:

> var x = 23

< undefined

> x

< '23'

> function exampleFunction() {

alert(x);

}

< undefined

> exampleFunction()

< undefined

> _

Global and Local Variables

Primarily, there are two main scopes in programming. JavaScript also adheres to that. The first one is global; the second one is local.

A variable has a global scope if it declared on the topmost level of your script; meaning, it was not declared inside a function or code block. Global variables are accessible everywhere in the script.

A variable that is declared inside a function will be considered a local variable. That local variable will be only available on the function that declared it.

However, not all variables used inside functions are considered local variables. If the variable was not declared, but was assigned a value, it will have a global scope. Nevertheless, it is best not to create global variables this way since it can be confusing, especially if you are writing the code together with another individual.

On the other hand, the lifespan of a global variable ends when the page closes. The lifespan of a local variable ends when the function that declares it finishes execution.

There is another way to create a global variable, and that is to use the window object, which will be discussed in the later chapters.

Note: It is preferred by developers to use or create as few global variables as possible. Mainly, usage of too many global variables can affect the performance of your script. Usage of disposable local variables is better to optimize the usage of memory resource of your computer. Use global variables if there is only a need.

Arguments and Parameters

If local variables can only be accessed by the function that declared it, how can other functions access them? Usually, some developers just take advantage of creating a global variable to fix that in a very convenient way. However, if you like to have optimized and well-performing scripts, you will want to use arguments and parameters in your function.

Parameters are local variables in a script that can receive arguments or values when invoked. For example:

> function simpleMultiplication(multiplier1, multiplier2) {

var product = multiplier1 * multiplier2;

alert(product);

}

< undefined

> simpleMultiplication(25, 5);

< undefined

> _

In this example, two parameters were created. Those are multiplier1 and multiplier2. Parameters are like local variables. The differences between them are parameters are declared together with the function’s identifier and they can receive arguments or values when the function is invoked.

In the example, the function simpleMultiplication was invoked and the invocation provided two arguments, 25 and 5. So, how can parameters and arguments solve the problem with scopes? Check this example:

> function simpleMultiplication(multiplier1, multiplier2) {

var product = multiplier1 * multiplier2;

showProduct(product);

}

< undefined

> function showProduct(number) {

alert(number);

}

< undefined

> simpleMultiplication(25, 5);

< undefined

> _

When this example is executed, the variable product will be provided to the showProduct() function, which effectively passes the value of a local variable to another function.

Some new developers who are not familiar with arguments and parameters do this by using global variables. For example:

> var product

< undefined

> var multiplier1

< undefined

> var multiplier2

< undefined

> function simpleMultiplication() {

product = multiplier1 * multiplier2;

showProduct();

}

< undefined

> function showProduct() {

alert(product);

}

< undefined

> multiplier1 = 25

< 25

> multiplier2 = 5

< 5

> simpleMultiplication();

< undefined

> _

With a quick glance, you can easily tell that using parameters and arguments over global variables is a much better, cleaner, and simpler way to allow functions to “communicate” and pass through values.

Function return

What would you do if you want the function to pass on a value? In the previous example, what would be a better way to shorten the code? The answer to those questions is the use of the return keyword and statement.

To make it simpler to pass on local variables, you can also take advantage of return statements. Return statements are there to let a statement that invokes a function to receive a value in “return”. For example:

> function simpleMultiplication(multiplier1, multiplier2) {

return multiplier1 * multiplier2;

}

< undefined

> simpleMultiplication(25, 5);

< 125

> alert(simpleMultiplication(25, 5));

< undefined

> _

As you might have noticed in the console, when you invoke the function this time, the console provides the answer for the function instead of the usual undefined. Receiving the answer (or the statement or the value of the expression that is indicated in the return statement) means that the function returns a value.

By the way, alert is also considered a function, a built-in function in JavaScript to be precise. However, unlike the new version of the simpleMultiplication example function, it does not return a value.

Anyway, when the alert function is called, it will provide a message box that contains the answer or the return value of the function. Simple, right?

Recap

In JavaScript, you can group statements into code blocks by placing them inside curly braces. Most developers do not do this since they usually take advantage of comments instead to organize their code blocks.

On the other hand, providing your code blocks with identifiers together with the function keyword makes them functions. The main difference between functions and code blocks is that functions will not be executed as long as they are not called or invoked.

When it comes to scope, there are two variable scopes in JavaScript: global and local. Declare a variable outside of functions, and they will have global scope. Declare variables in functions, and they will have local scope.

Passing through variable values in and out of functions can be eased by using parameters, arguments, and return statements. Do remember that it is highly discouraged to use global variables, especially if your script is large due to performance issues.