Basic Introduction to Functions in JavaScript
Tags: javascript, beginners
Published: 2022-07-11 03:40:16

Functions are one of the foundational components in JavaScript programming.  Functions give us a way to do many things including structuring larger programs; reducing repetition; return values; associate names with subprograms or useful code blocks that will execute an action we may require multiple times under different context within our code, sometimes referred to as “helper functions”; and isolating different subprograms and actions from each other.  

<u>What is a function?</u>

A **function** is created with an  expression that starts with the keyword function. Functions are named and that name becomes associated with whatever we tell the function we want it to do. Functions also have **parameters** and a **body**, which contains the statements that are going to be executed. Functions only execute their actions when explicitly told to do so which is referred to as calling or invoking. Invoking a function requires us to tell the program which function we want it to execute by using its variable name and an **argument**. Functions can be written using differing styles of notation, in this piece I will be dealing with declaration notation with the others considered outside the scope of this writing.

Base function syntax:
function name( parameter1 ) {body}

Base function invocation:
name( argument )

A quick note on naming variables in functions and naming in general in JavaScript.  The convention for naming in JavaScript is camelCase, that is, the first word in a compound variable name is lowercase and all following words are uppercase. You can use any letters or number you would like and can also use the $ and _ symbols as well. However there are quite a few words that you should not use as variable names because those words are considered reserved, either because they are currently predefined in JavaScript or they will be in the future.  There are also words that used to be reserved but have been removed from the reserved list. However, it is not recommended to use words removed from the list because it may cause compatibility issues for instances when the newest version of JavaScript is not fully supported. A list of reserved words and more information can be found here: [https://www.w3schools.com/js/js_reserved.asp](https://www.w3schools.com/js/js_reserved.asp)

<u>Parameters, Arguments, and Return in Functions</u>

A function can have multiple parameters or no parameters at all. In the following example, coinDrop does not list any parameter names, total has 2 parameters, and skippedStone below lists one:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/blyv0cnf7udpi70zk0t2.jpg)

A parameter is a placeholder that stores whatever value is passed to it as an argument when it is invoked.  

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e3rw57lun8m89qp3af5x.jpg)

In the example above when we pass the argument “Splash!” to our function skippedStone the console log will display “Splash!”.  Arguments are the actual values that we include in our invocation and are passed to the function, whereas, parameters are the named references (i.e. placeholders) where we store those passed-in values. This allows for flexibility in the creation and usage of JavaScript functions as an argument can be any JavaScript expression, from numbers or a simple string to another entire function.   

Some functions produce a value, such as total, and some don’t, such as coinDrop, whose only result is a side effect. A return statement, starting with the _return_ keyword determines the value the function returns. Setting up your function so that it returns a value means that value is available to be used elsewhere in your program. A _return _keyword without an expression after it will cause the function to return _undefined_. Functions that don’t have a return statement at all, such as coinDrop, similarly return _undefined_.

<u>Scope in Functions</u>

Scope is a complex topic and here we are only going to touch on the very basics. Every variable in JavaScript has a scope or where it can be seen and accessed by the program. For those variables defined outside of any function or code block, the scope is considered global and the whole program has access to these variables and can be referenced anywhere in the program. 
 
Variables that are created for function parameters or declared inside a function can be referenced only inside that particular function. The scope in this instance is considered to be local as only that function can access it. Finally, those variables that are declared with _let_ and _const_ inside a particular block are visible only within that block. Therefore, given a function with a loop in which variables were declared, the variables would not be visible to the code before or after that particular block.

What is visible or within scope inside a block is determined by the placement of that block within the program text.  All local scopes can also see all the local scopes that contain it, and all scopes can see the global scope. A way to think about this if you are having trouble wrapping your mind around it, is to consider each function or code block having one-way glass around it, those on the inside can see out, but those outside cannot see in. 

<u>Conclusion </u>  

Functions are one of the most utilized and versatile tools in JavaScript. Having a good foundational understanding of them can help improve your ability to code dynamically, chase down errors, avoid unnecessary repetition (e.g. DRY code), participate in refactoring, and just make you a better programmer in general. So go and experiment with them, break your code and savor the feeling when you finally get it to work! Good luck and happy coding!





<u>References</u>

M. Haverbeke, Eloquent javascript: A modern introduction to programming, 3rd ed. San Francisco, CA: No Starch Press, 2018.

Flatiron School, “Review: Functions,” in Flatiron Canvas Dashboard, 2022.