Bo dinglesTM - -   Bright Lightbulb Graphic Ideas   - -

The Web Developer Bootcamp 2024

Colt Steele

Back to JavaScript Index Page


JavaScript Functions
JavaScript Functions References

JavaScript Functions Intro PDF

JavaScript Functions Part 2 PDF

W3Schools JavaScript Functions

MDN JavaScript Functions

Geeks4Geeks JavaScript Functions

Functions are one of the fundamental building blocks in JavaScript. Functions are reusable blocks of code that perform a specific task. You define it once, and then you can run (or “call”) it whenever you need that task done in your program.

For a procedure to qualify as a function, it should take some input and return an output, where there is some obvious relationship between the input and the output.


Basic Syntax

A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses (). Function names can contain letters, digits, underscores, and dollar signs (same rules as variables). The parentheses may include parameter names separated by commas: (parameter1, parameter2, ...). The code to be executed, by the function, is placed inside curly brackets: {}

  • function funcName(parameter1, parameter2, parameter3) {
    • code to be executed
  • }

For example, if we wanted we could write a function to return a random number, say between 1 and 10. Remember:

  • Math.random() returns a decimal number between 0 and 1 (not including 1)
  • Math.random() * 10 returns a decimal number between 0 and 10 (not including 10)
  • Math.floor() would return only integers so, 0 to 10 (not including 10)
  • if you want to start at 1 instead of 0, and include 10: you add 1
  • so our needed formula is Math.floor(Math.random() * 10) + 1

So the function would be:

  • function getRandomNum() {
    • Math.floor(Math.random() * 10) + 1
  • }

and everytime we call this function getRandomNum() it would return a random number between 1 and 10.


Arguments

With function, you can pass in arguments which are variables that are used within the function. Let's create a new function called name:

  • function name(fname) {
    • console.log(`First Name: ${fname}`);
  • }

We are using fname as a variable for use within the function,and if we paass in a name for the argument

  • name('Ben')
the ouput would be: First Name: Ben


We can also pass multiple arguments into a function like so:

  • function name(fName, lName) {
    • console.log(`Your name is ${fName} ${lName}`);
  • }

and if we pass in the arguments:

  • name('Ben', 'Franklin')
the ouput would be: Your name is Ben Franklin


return

We have been using console.log() to send our ouput to the screen, but what if we wanted to send the results of the function back to the code for use within the code. We would do this with the return statement.

I the prevous example instead of outputting Ben Franklin to the screen, we could return it to the code as a variable return `Your name is ${fName} ${lName}`;

You can assign this variable within the function:

  • let wholeName = `fName lName';
  • return wholeName;
note*: the RETURN statement terminates the function so it should be the last statement in the function.


Scope

W3Schools JavaScript Scope

MDN JavaScript Scope

Scope refers to where a variable is defined and what parts of the code will have access to that variable. JavaScript variables have 3 types of scope:

  • Block scope refers to a variable that is created inside of a block of code, and is only useable inside that block of code.
  • Function scope refers to a variable that is created inside a function, and is only useable inside the function.
  • Global scope refers to a variable that is declared outside of a function. This variable is global in nature and would be available everywhere int he code.


*Notes: Block and Function Scope

When you assign variables inside of brackets {}, using const or let, the scope is inside the curly brackets ONLY, and the variables will NOT be available outside of the curly brackets. For example:

  • function fullName() {
    • const fname = 'Benny';
    • let lname = 'Hill';
  • }
  • console.log(fname + lname);
This code snippet will output NOTHING because the variables fname and lname are NOT accessible outside of the curly brackets {}.


However, when you use var to define the variable, this would make the variable accessable outside of the curly bvrackets {}. For example:

  • function fullName() {
    • var fname = 'Benny';
  • }
  • console.log(fname);
would output Benny because the var designation make the variable available outside of the curly brackets {}.


In Summary, var is an older keyword and is not used much anymore. const and let were created specifically for "SCOPING" purposes and are used most of the time.



Function Expressions

are a way of assigning a function to a variable. If we have a basic function like:

  • function add(x, y) {
    • return x + y;
  • }
when you call the function add(3, 4); it would return 7. but we can rewrite the function and assign it to a variable, like so:
  • const add = function(x, y) {
    • return x + y;
  • }
which would run exactly the same and return 7, but add is NOW a variable and can be used as such.


this

this is a keyword and it refers to the context where a piece of code, such as a function's body, is supposed to run. Most typically, it is used in object methods, where this refers to the object that the method is attached to, thus allowing the same method to be reused on different objects. For example, if you tried to run this object:

  • const hen = {
    • name: 'Helen',
    • eggCount: 0,
    • layAnEgg() {
      • eggCount += 1;
      • return eggCount
    • }
  • }
it would return an error because eggCount was defined before the layAnEgg function and is limited by scope to only be accessable outside of that function, so the function is trying to use a variable that has not been defined within the function (limited by scope).

This error can be overcome by using the keyword this. If we modify our object like so:

  • const hen = {
    • name: 'Helen',
    • eggCount: 0,
    • layAnEgg() {
      • this.eggCount += 1;
      • return eggCount
    • }
  • }
then everything works because this refers to this object and all of the variables available to the object are available to the entire object contents.

However, the this keyword has to be very specific in nature. It refers soley to the object. In our example, this refers only to the object hen, and is called using hen.this. The "scope" of this always refers to the object name to the left of this. So if a object name is omitted, then this is refering to the root of the DOM and can produce unecpected results.

More information at W3Schools this and MDN this.


try/catch

try/catch is a method of "trapping for Errors" and determining how to respond to the error to prevent your code from "breaking" and your script to stop running. Try/catch is not specific to functions, but is very useful in all aspects of JavaScript coding.

The basic format is:

  • try {
    • block of code
  • } catch {
    • code to deal with error
  • }

More information at W3Schools try/catch and MDN try/catch.



setInterval

W3Schools JavaScript setInterval

MDN JavaScript setInterval

setInterval calls a function or executes a code snippet, with a fixed time delay between each call(in milliseconds).

  • The setInterval() method continues calling the function until clearInterval() is called, or the window is closed.
  • Use the clearInterval() method to clear a timer set with the setInterval method.
  • (1000 milliseconds = 1 second)



Back to Top