JavaScript Functions

Functions are similar to methods or actions that our program can take. Functions allow us to put together code that we will execute when that function is called or invoked. In the Javascript programming language functions are considered an object that contains a sequence of JavaScript statements.

Join the Dark Side!

Example of a function

function darkSideOfTheForce( ) {

console.log(“You don’t know the power of the Dark Side of the force”);

console.log(“Join the Dark Side of the force!”);

}

Break Down of JavaScript Function

When you create a function you must start the function by writing function and the name of the function. The name of the function should must follow camelcase format aka the first word starts with lowercase and every subsequent word is upper case. If you look at the function name above. you will see its called darkSideOfTheForce. When you create a function it is called a function declaration. The () in the function executes the function without the () the code inside the function will not execute.

Passing Arguments in a function

A function can also take in arguments similar to methods in other programming languages like Ruby. We can then pass those arguments into the code of the function using string interpolation. A string interpolation is declared using ${ }. When you use string interpolation inside a string you must use backticks ` to contain the string. Let’s refactor our previous function so that it takes an argument and we pass the argument into the console log of the function.

function darkSideOfTheForce (person) {

console.log(`${person} you don’t know the power of the force.`);

console.log(`${person} join the Dark Side of the force!`);

}

When using parameters in JavaScript for functions you must make sure you set a value for the parameter or it will automatically default to undefined which can led to a bug.

Return Values in Parameters

When you call a function you can also give it a return value. A return value sends back some information to where the function was called. It is important to designate the return as something related to the function itself. In Javascript when it encounters a return statement it will return whatever is to the right of the return value. When JavaScript reaches the return in the code, no other code behavior will occur. Return values can be also stored to variable or used as inputs to other functions.

function darkSideOfTheForce (person) {

console.log(`${person} you don’t know the power of the force.`);

console.log(`${person} join the Dark Side of the force!`);

return ``

}

response = darkSideOfTheForce (“Luke”);

console.log(response);

First Class Functions

In JavaScript we must make distinctions between expressions and statements. A statement is a piece of code that accomplishes something without producing a value. An expression is code that produces a value. It is similar to the Millennium Falcon where the ship itself is a statement (it is designed to accomplish something). The Millennium Falcon is an expression when it produces something like making the jump to hyperspace.

Millennium Falcon hyperspace jump.

Common Keywords in JavaScript

declaring a variable: const, let, var

Iterators: for, for…of, for…in, while

Control flow: if…else, switch, break

Debugging: debugger

All of these common keywords form statements. These common keywords help to lay the framework to make expressions. If statements for example by themselves are NOT expressive. They are only expressive when they produce a value.

Example

if (false) { 4 +10}

Expressions can be assigned to variables but because an if statement itself is not an expression it cannot be assigned to a variable.

const vader = 2 +1

vader => 3

const vader = if (false) { 4 +10} => Error

Statements are used to hold, iterate, control and debug data while expressions are used to produce data.

Function Declarations vs Expressions

Function Declarations are when we create a function that doesn’t produce a value.

function myFunc() {}

When this function is the first thing in a line of code it is a function declaration. It does not produce a value when it is the first line of code. When we place this function anywhere else besides the start of the first line of code it becomes a function expression and returns itself (function) as a value.

(function() {}); //parentheses around a function are only required if it would otherwise be the first code in a line of code.

=> ƒ () {}

Special Properties of First Class Functions in JavaScript

JavaScript is unique in that it treats a function itself as an object. An object is something that encapsulates certain properties. In JavaScript functions can be treated the same way as objects are treated. Functions in JavaScript are called first-class citizens because they can be treated the same way as other objects or values.

Things we can do with functions

  1. A function can be assigned to a variable.

const func = function() {return 2 + 1}

2. A function can be stored in a data structure. In the example below we have an array of functions!

const skwalkerFamily= [

function() {

console.log(‘Luke’);

},

function() {

console.log(‘Leia’);

},

function() {

console.log(‘Anakin’);

},

function() {

console.log(‘R2D2’);

}

]

3. A function can be the return value of another function.

function(luke) {

return function(leia) {

return ` ${luke}and ${leia}`

}

}

4. A function can be passed as argument to another function.

function theForce (fn) {

console.log(“The force is strong with this one”)

return fn

}

All these examples are similar to what we can do with a value such as a number. We can take the number 2 for example and do the above four things to it.

Anonymous Functions

Anonymous functions are functions that are not given a name. A function does not have to be named when they are stored in a variable. They are always called or invoked using the variable name.

Example

let darkSideRecruitment = function ( ) {

console.log(“You don’t know the power of the Dark Side of the force”);

console.log(“Join the Dark Side of the force!”);

}

More Interesting Things we can do with Functions

Since functions are special objects in JavaScript we can add properties and access those properties.

const solo = function () {

console.log(“Great Kid, Don’t Get Cocky..”);

}

solo.profession = “smuggler”

console.log(“Han Solo’s profession is”, solo.profession)

LOG: Han Solo’s profession is smuggler

Function Expressions and Hoisting

In many programming languages the code is executed from top to bottom. If you wanted to use a function in your code you must declare it first before you use it. This makes sense because you can’t use something that doesn’t exit.

Example

function yoda ( ) {

return “You must unlearn what you have learned.”

}

yoda( )

=> ““You must unlearn what you have learned.”

However, in JavaScript calling the function before it is declared does not cause any issues.

yoda( )

function yoda ( ) {

return “You must unlearn what you have learned.”

}

You must unlearn what you learned from other programming languages.

JavaScript Compilation and Execution Phase

JavaScript goes through a two step process when it comes to executing a code. It goes through a compilation phase where it doesn’t invoke or call functions but stores the declared function in memory along with any variables. In the execution phase JavaScript will invoke or call the function which was already created during the compilation phase.

This process is called hoisting because it appears as if the function declarations are being hoisted or moved up to the top. In order to avoid any issues with function hoisting declare the functions at the top of your code

Yoda hoisting X Wing!

Function expressions are NOT hoisted. They are ignored during the compilation phase and they are evaluated during the execution phase. If you try to express a constant variable that was assigned an expressed function before its assignment it will cause an error.

sayDeathStar()

const sayDeathStar = function() {
console.log(“Death Star”);
}

//ERROR not defined

The const sayDeathStar does not get hoisted because it is a constant variable. Constant variables don’t get hoisted. When you try to express it will say that the variable is not defined. If you use var instead of const for this example you will have the variable hoisted but it will be undefined until it reaches the line where the variable is assigned. You cant call or invoke undefined so the console will throw another error stating the variable is not a function.

sayDeathStar()

var sayDeathStar = function() {
console.log(“Death Star”);
}

//ERROR sayDeathStar is not a function

Passing by Reference for Functions

Like all JavaScript objects functions are passed by reference. A function/object is stored in the computers memory. When you assign a function or an object to a variable the variable points to the memory location for that object. If you reassign the function/object to a different variable you are still pointing to the same memory location of the object. If you modify the function/object you are modifying the function based on where it is stored in memory. If you reassign a variable to a different function/object you are pointing to a new function/object.

Example

let anakin= function() {

console.log(“I’m a Jedi.”)

}

const jedi = anakin

let anakin = function() {

console.log(“I’m Darth Vader.”);

};

jedi();

// LOG: I’m a Jedi.

anakin();

// LOG: I’m Darth Vader.

Functions in JavaScript is the foundation on which we use JavaScript to manipulate code to our liking. Mastering functions in JavaScript will make you a web development Jedi Master!

Much to learn about functions you still have.

Aspiring Software Engineer and Gamer.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store