DEV Community

Cover image for Functions - JavaScript Core Concepts
Angeline Wang
Angeline Wang

Posted on

Functions - JavaScript Core Concepts

The Functions & Methods Section of my JavaScript Core Concepts Series is divided into 6 Parts:

Part 1 Functions
Part 2 Classes
Part 3 Methods
Part 4 Callback Methods
Part 5 Scope
Part 6 Hoisting

Functions

Part 1 What is a Function?

Here are a few definitions:

  1. Block of code
    = Performs an action or returns a value

  2. Custom code
    = Defined by programmers and are reusable
    → Can make programs more modular & efficient

...

Part 2 Function Definition

Option 1: function keyword

Code Example
function newEvent() {
    console.log(‘New event created!’)
}
Enter fullscreen mode Exit fullscreen mode
Application
  1. Begins with function keyword

  2. Followed by name of function

  3. Function names follow same rules as variables
    = Can contain letters, numbers, underscores and dollar signs
    → Frequently written in camel case
    → Name is followed by a set of parentheses: Which can be used for optional parameters

  4. Code of function
    = Contained in curly brackets
    → Like a for statement or an if statement

  5. Nothing will happen
    = No code will execute
    → Until the function is invoked/called

Option 2: Function Expressions

Creation

= Assign a Function to a Variable

Code Example

= Using add example above
→ Directly apply returned value to a variable (sum)

const sum = function add(x, y) {
    return x + y;
}

// Invoked function to find the sum
sum(20, 5);
Enter fullscreen mode Exit fullscreen mode

= Output: 25
sum Constant Variable is a Function

Adding Concision

= Turn it into an Anonymous Function (aka Unnamed Function)
→ Currently, function name is add
→ But with Function Expressions, it is not needed to name the Function

So the Name is usually omitted like below:

Code Example

const sum = function(x, y) {
    return x + y;
}

//Invoke function to find the sum
sum(100, 3);
Enter fullscreen mode Exit fullscreen mode

= Name of function: add is removed
→ Turned it into an anonymous function

Preserving Function Name

= Could be used to help debugging
→ However, the Name is usually omitted

Option 3: Arrow Functions

Purpose

= Newer, more concise method to define a function as of ECMAScript 6
→ Represented by an Equals Sign, followed by a greater than sign: =>
= Always anonymous functions
→ They are a type of function expression

Basic Example

= Find product of 2 numbers:

const multiply = (x, y) => {
    return x * y;
}

// Invoke function to find product
multiply(30, 4);
Enter fullscreen mode Exit fullscreen mode

= Instead of writing out the keyword function
→ Used => arrow: Indicate a function
= Otherwise, it works similarly to a regular function expression
→ With some advanced differences

Benefits
  1. Concise Syntax

  2. Implicit Returns
    = Allows us to write one-liners

  3. No rebinding the value of this when you use an Arrow Function inside another Function
    = Helpful for doing things like click handlers etc.

Application
Transformation to Arrow Function

= Turn into an Arrow Function

  1. Delete keyword function

  2. Add a fat arrow: =>
    = Which does the same thing as function
    → And when console.logged, you get the same thing

  3. Remove parentheses if you only have 1 parameter
    = Though you can keep the parenthesis as a stylistic choice
    → Example: In callback functions ie map function it’s nice to leave them out for clean syntax

1 Parameter

= Parentheses can be excluded
Example: Squaring x, which only requires 1 number to be passed as an argument

= Parentheses have been omitted:

Code Example

const square = x => {
    return x * x;
}   

square(8);
Enter fullscreen mode Exit fullscreen mode

= Output: 64
→ These example only contain a return statement
→ Thus: Arrow functions allow syntax to be reduced even further

Single-line return

If function is only a single line return:
= Both curly brackets and return statement can be omitted

Code Example

const square = x => x * x;

square(10);
Enter fullscreen mode Exit fullscreen mode

= Output: 100

No Parameter/Argument

= An empty set of parentheses is still required in the arrow functions
→ Could also use an underscore _ in the place of ()
→ Underscore = Throwaway variable: B/c we’re actually creating a variable called _ but not using it
_ does not have any significance at all

= Any variable name can be used
→ Just thrown away (because there’s no parenthese around it)

Code Example

names.map(_ => `Angeline Wang`);
names.map(x => `Angeline Wang`);
names.map(boo_yaa => `Angeline Wang`);
Enter fullscreen mode Exit fullscreen mode

= You can do this however you want

Return
Implicit vs Explicit

Implicit Return

  1. Many callback functions written in JS are just one liners
    = Where we just return something immediately in one line
    → Don’t need a whole bunch of lines

  2. Only purpose of arrow function is to return something
    = No need for return keyword

Implicit Return in Arrow Functions

  1. Delete the return

  2. Put it up on all of one line

  3. Delete the curly brackets
    = Going to be an implicit return
    → Means we do not need to specify what we are returning
    → Will be assumed that we are doing so
    console.log will see the same thing again

Explicit Return
= Explicitly write return for what you want to return

Named vs Anonymous Function
Named Function

= Function has a Name attached to it

Named Example
This is what a Named Function looks like:

function sayMyName(name) {
    alert(`Hello ${name}`);
}
Enter fullscreen mode Exit fullscreen mode

Benefits of Naming Functions
= In the case of a Stack trace: When you have an Error
→ To figure out where something has gone wrong

= Line num may not be very helpful
→ Need to know actually the name of the function it got called in

Arrow Function Anonymity

But, if an Arrow Function is used
= You cannot name them
→ None of arrow functions have a name
→ Arrow Functions are always Anonymous Functions

Solution
= Can put an arrow function inside a variable
→ This means that you would be passing the arrow function a name and creating a function declaration that way

Example

const sayMyName = (name) => {alert(`Hello ${name}!`)}

sayMyName(‘Angeline Wang’);
Enter fullscreen mode Exit fullscreen mode

= This is still an anonymous function & it will not give us very good stack traces
→ But if you’re not concerned about stack traces: you can do this

Which Option to Choose

= The 3 different types of syntax result in the same output
→ Which to use depends on preference/Company coding standards to decide how you’ll structure own functions

...

Part 3 Function Invocation

How to Call a Function

= Write name of function followed by parentheses
→ And can be reused as many times as you want

Code Example

newEvent();
Enter fullscreen mode Exit fullscreen mode

...

Part 4 Function Parameters

Definition

= Input that gets passed into functions as names and behave as local variables

Purpose

  1. Make code more dynamic by creating dynamic functions

  2. Add additional functionality

  3. Make code more flexible

Code Example

Example: Add date of event

function newEvent(date) {
    console.log(`New event on ${date}!`);
}
Enter fullscreen mode Exit fullscreen mode

= Name of function is newEvents
→ Now have single parameter inside the parentheses
→ Name of parameter follows same rules as naming a Variable

Use Parameter inside Function

Example

= To use parameters inside a string:
→ Instead of a Static String: Add a Template Literal String
Contains Parameter
Not behaving as a Local Variable

Parameter Value Assignment

  1. If the parameter is not defined anywhere
    = A value can be assigned to it when invoking the function
    → Value is placed w/in Parentheses of Function Call
    → It is used as the Argument

  2. Every time the parameter is used within the Function
    = The value passed during Function Call is used

Real World Use Case

= For example, the function would pull the username from a database instead of directly supplying the name as an argument value

...

Part 5 Declarations inside Functions

= Variables can be declared inside functions
→ Known as Local Variables
They will only exist inside the scope of their own Function Block

Variable Scope

= Determines variables’ accessibility
→ ie Variables defined inside a Function: Not accessible outside function
But can be used at the same time as the Function is used throughout the program

...

Part 6 Return Values

Amount of Parameters Allowed

= > 1 Parameter can be used in a Function
→ You can pass multiple values into a Function and Return a value

Code Example

= Create function to find sum of 2 values
→ Represented by x and y

// Initialize add function
function add(x, y) {
    return x + y;
}

// Invoke function to find the sum
add(9, 7);
Enter fullscreen mode Exit fullscreen mode

= Defined function with parameters x and y
→ Then passed the values 9 and 7 to the function
→ When we run the program, we’ll received sum of those numbers as the output

return Keyword

= When the return keyword is used
→ The function stops executing:
Value of the Expression is returned
Output will be where the Function was invoked
Value can be used straight away
Or placed into a Variable

...

Part 7 Pure Functions

Definition

It needs to pass 2 requirements:

1. Always returns same result

= If same arguments are passed it
→ Does not depend on any state, or data change during program execution
= Must only depend on input arguments

2. Does not produce any observable side effects

= ie Network requests, input and output devices, or data mutation

Observable Side Effects

= Any interaction with outside world
→ From within a function
= Could be anything from changing a variable that exists outside the function
→ To calling another method from within a function

Pure Function calling a Pure Function

= Not a side effect
→ And the calling function is still pure

Examples of side effects:
  • Making a HTTP request
  • Mutating data
  • Printing to a screen or console
  • DOM Query/Manipulation
  • Math.random()
  • Getting the current time
Characteristics of Side effects:
  • Not bad in and of themselves
  • They are often required
  • But for a function to be called pure, it must not contain any
  • Not all functions need to be, or should be, pure

Example of Pure Function

= Calculating price of a product including tax

function priceAfterTax(productPrice) {
    return (productPrice * 0.20) + productPrice;
}
Enter fullscreen mode Exit fullscreen mode

= Passes 1 and 2 of the requirements for function to be pure:
→ Does not depend on any external input
→ Does not mutate any data
→ Does not have any side effects

= If you run this function with same input 100 million times
→ It will always produce the same result

Example of Impure Function

var tax = 20;

function calculateTax(productPrice) {
    return (producePrice * (tax/100)) + productPrice;
}
Enter fullscreen mode Exit fullscreen mode

= This is impure because it depends on an external tax variable
→ Pure functions cannot depend on outside variables
→ This function fails one of the requirements, so it is impure

Use Cases

  1. Heavily used in Functional Programming
    = And libraries like ReactJS and Redux require use of pure functions

  2. Regular JS that does not depend on single programming paradigm
    = Can mix pure and impure functions

  3. Not all functions need to be or should be pure
    → Example: Event handler for a button press that manipulates the DOM should not be pure
    → Example: Event handler can call other pure functions which will reduce the number of impure functions in your app

  4. Testing & Refactoring
    = Benefit of using pure functions: Immediately testable
    → Always product same result if pass same arguments

  5. Make maintaining & refactoring code easier
    = Can change pure function & not worry about unintended side effects altering the entire app & making debugging very difficult
    → Better quality code, cleaner way of working

  6. Pure functions are not limited to JavaScript

Resources for Further Exploration:

How To Define Functions in JavaScript

JavaScript: What Are Pure Functions And Why Use Them? By James Jeffery

Wes Bos: JavaScript Arrow Functions Introduction

Top comments (0)