A Really Quick Refresher On JavaScript Function Concepts

by kleamerkuri
Refresher on JavaScript function concepts.

If you’ve been coding in JavaScript for a while, you know that functions are the building blocks of this powerful language.

Hence why it’s always good to revisit the basics and ensure you have a solid foundation šŸ’ā€ā™€ļø

In this blog post, we’ll take a trip down memory lane to refresh your knowledge of JavaScript function concepts such as:

  • understanding block scope
  • leveraging methods
  • mastering expressions
  • assigning default parameters

So, grab your favorite coding beverage, and let’s embark on this journey to level up your JavaScript game!

But first, hereā€™s a tantalizing teaser for ya: “Did you know that functions can return functions in JavaScript?”

Intrigued?

Read on to uncover the secrets of JavaScript functions!

Return

The return keyword returns values by capturing output and allowing its storage in a variable.

Since return stops the execution of a function, nothing after the return statement runs making it so a function can only return one thing.

That said, you can have more than one return inside of a single function usually with a conditional expression.

In such a case, the function will render only one of the statements based on which meets the conditional.

function sayHi(name) {
  if(name === 'Klea') {
    return 'Why, hello there sister Klea!';
  } else {
    return `Hi, I'm ${name}. It's a pleasure to meet ya!`;
  }
}

let person = sayHi('Klea'); // "Why, hello there sister Klea!"

// Re-assign value to person
person = sayHi('DM');
console.log(person); //"Hi, I'm DM. It's a pleasure to meet ya!"

Tip ā€¼ļø
Donā€™t place any code you want to take affect after a return statement! The return will terminate the function regardless of whether thereā€™s more code after its declaration.

As a fun fact, I sometimes use return to troubleshoot bugs in code. Itā€™s way faster than commenting out or, god forbid, deleting lines (hint: donā€™t delete unless you desire to regret).

See it in action šŸ‘‰ How To Build An Amazing Custom Datepicker

Block scope

Block scope refers to statements within curly braces like function example() { // BLOCK SCOPE }.

Variables declared with the newer ES6 syntax let and const keys arenā€™t accessible outside of the block. Thatā€™s because theyā€™re strictly scoped within that block.

Thatā€™s not the case with var keyword as it scopes to functions, but not to blocks.

A way to access strictly scoped variables is by returning them and storing the return value(s) in a variable.

Note šŸ¤Ø
If youā€™re wondering why bother with let and const when they have limitations, consider the bugs youā€™ll run into with the easily mutable var .

Now, if a function is inside of another function, you need to call the nested function in the parent for the nested to execute when calling the parent.

This is known as lexical scope, where you can access a variable in the parent function (otherwise put, in the area of definition).

The inner function has access to the variable in its parent but not the other way around.

Function expressions

A function expression is created when storing a function in a variable without giving that function a name.

Example: const myFunc = function () { // do something }

You execute a function expression the same way as you would a named function. But, instead of a function name, use the variable name.

Executing the example looks like this: myFunc() .

Note: ES6 introduced arrow functions which are function expressions with slightly altered syntax that let you skip the function keyword all together!

Read: 14 ES6 Features You Need To Know To Refresh Your JavaScript

Default parameters

Did you know you can add a default value to a function parameter in case the user doesnā€™t specify any?

Example: const exFunc = (a, b=1) => a * b;

In the example:

  • a is a required parameter. The console will throw errors on function execution if itā€™s missing.
  • b is an optional parameter. The default value of 1 is used if the argument is omitted on function execution.

Tip: The order of parameters matters since parameters are set left-to-right so default parameters must come after parameters that donā€™t have defaults!

Higher-Order Functions

Higher-order functions are functions that work on, or with, other functions.

A function specified inline is returned by a parent function but isnā€™t executed unless you capture it as a value in a variable.

We can break down a higher-order function in two steps:

  1. Store the parent function in a variable. This action merely stores the inner function thatā€™s the return value.
  2. Execute the variable from above. This action actually fires the inner function.
function outFunc(a, b) {
    return function(c) {
        return c >= a && c <= b;
    }
}

// Execute by...
let inFunc = outFunc(#, #); // returns function as value
inFunc(#); 

Methods

A method is a function placed as a property in an object (like those found in class declarations).

An example would be Math.random() where Math is the object and random() is the property with a function value.

Some other good examples of methods are the built-in setTimeout() and setInterval() methods.

  • setTimeout takes two arguments: (1) a callback function and (2) time in milliseconds. The callback function will execute once after the number of milliseconds is up.
  • setInterval has the same syntax as setTimeout, but it keeps on firing after the specified time elapses.

See it in action šŸ‘‰ How To Create An Animated Message With HTML, CSS, And JavaScript

Both setTimeout and setInterval return an ID that you can pass into clearTimeout() or clearInterval() to cancel a previous timeout or interval.

Tip: Capture the returned ID from setTimeout or setInterval using a variable!

As a little example, we can use setTimeout to capture a userā€™s complete input instead of every keystroke.

If you were to log the value of an input based on what is entered, youā€™d get every keystroke.

// HTML šŸ‘‡ (so we can see things)
<input type="text" />

// JS to capture a user's input
document.querySelector('input').addEventListener('input', (e) => {
  console.log(e.target.value); // Captures every keystroke
});
Capturing every keystroke setTimeout.

Not quite what we were going for since the goal is the complete input šŸ™…ā€ā™€ļø

To get the input in its entirety, use setTimeout like so:

// Altered JS code (to do what we want)

let timeout; 

document.querySelector('input').addEventListener('input', (e) => {  
  clearTimeout(timeout);
  timeout = setTimeout( () => {
    console.log(e.target.value);
  }, 500);
});
Capture user input setTimeout debouncing

Breaking down the code:

  • timeout: A variable that captures the ID returned by setTimeout . This is defined outside of the functional block because we donā€™t want to declare it on every keystroke!
  • clearTimeout(timeout): Clears any existing timeouts so we donā€™t get the collected keystrokes on every keystroke.
  • setTimeout( ()=>{}, 500): Collects all keystrokes until the given time limit pause is reached.

Hint: Try / Catch

Use try…catch to avoid ā€œuncaught errorā€ messages.

The basic syntax is:

try {
    // something to try
} catch(err) {
    // show if above fails
}

The try{} block executes first but, should there be an error of any sort, the catch(err){} block kicks in with a potential variable that stores the error.

Thereā€™s also a finally{} block chained at the end though itā€™s optional since it fires regardless of error or exception.


With this, our quick refresher comes to an end.
See, I told ya it was really quick šŸ˜

‘Till the next one!

Related Posts