Loading...

Functions in JavaScript

Functions Fundamentals

Functions are pieces of code that perform actions. There are both functions built into JavaScript and an almost limitless number of functions a developer can create.

The Anatomy of a Function

  • Function can be created using the function keyword, usually followed by a unique name (though a name is not required), followed by () and then { }
  • Inside of the (), you can set parameters. These parameters are optional, but, if used, allow for data to be transferred in to the function to be used.
  • Functions usually end with the keyword return. This keyword signals the JavaScript engine to stop processing the function and will take any data listed after the return keyword and send it back to where the function was invoked. Essentially, return is just the output of the function.
  • Functions are usually invoked by using the function's name followed by double-parenthesis ()
  • When invoking a function, any data put between the parenthesis () are called arguments. These arguments will be sent to the function to be used.

Here are a few of the function that are built in to JavaScript

parseInt(string, radix)
parseFloat(string)
isNaN(number)
isFinite(number)
decodeURI(encodedURI)
decodeURIComponent(encodedURIComponent)
encodeURI(uri)
encodeURIComponent(uriComponent)
escape(string)
unescape(string)

Here is what a custom function can look like.


//	A custom function
function myFunctionName(aPerameter) {
    //	Here is where the actions go
    console.log('Here is what you entered:', aPerameter);
}

//	Run it like this
myFunctionName('This will work!');

Argument Defaults

Inside the parenthesis we can pass arguments for the function to use, but, sometimes, we may want to invoke the function without arguments. The function can be structured to work regardless of the arguments, or we can set default values.

function findingSomeone(name = 'someone', age = 29, town = 'somewhere') {
    return `I am looking for ${name}. He is ${age} years old and comes from ${town}.`
}

//	Running the function without arguments
function findingSomeone(name = 'somone', age = 29, town = 'somewhere') {
    return `I am looking for ${name}. He is ${age} years old and comes from ${town}.`
}

//	Running the function without arguments
findingSomeone();
//	RESULT: 'I am looking for somone. He is 29 years old and comes from somewhere.'

//	Now with arguments being passed
const theName = 'Cyrus';
const theAge = 43;
const theTown = 'Cincinnati';

findingSomeone(theName, theAge, theTown);
//	RESULT: 'I am looking for Cyrus. He is 43 years old and comes from Cincinnati.'    findingSomeone();
//	RESULT: 'I am looking for somone. He is 29 years old and comes from somewhere.'

//	Now with arguments being passed
const theName = 'Cyrus';
const theAge = 43;
const theTown = 'Cincinnati';

findingSomeone(theName, theAge, theTown);
//	RESULT: 'I am looking for Cyrus. He is 43 years old and comes from Cincinnati.'

Switch Function

switch function - Programmatically make a selection. Each option is called a case.

let n = "Mike";
switch (n) {
    case "John":
        outputSheet.innerHTML += '***case 1 - ' + n;
        break;

    case "Mike":
        outputSheet.innerHTML += 'Switch Functions: Use CASE to determine outcome   |   Result: ***case 2 -' + n + ' ';
        break;;
    case "Tom":
        outputSheet.innerHTML += '***case 3 -' + n;
        break;
}

↓
RESULT↓
Switch Functions output: ** *
    case 2 - Mike
                        

Overloading Functions

Overloading Functions - When more parameters are passed than requested. For this, the arguments object will contain all of the parameters passed.

function SomeFunctOverload(param1, param2) {
    const numberOfPassedArgs = arguments.length;
    if (numberOfPassedArgs <= 3) {
        //...code
    } else {
        outputSheet.innerHTML += 'This shows the function call overloaded the function parameters.';
    }
}

// Overloaded function invoking												 	
SomeFunctOverload('data1', 'data2', 'data3', 'data4');

↓
RESULT↓
OUTPUT: This shows the
function call overloaded the
function parameters.
                        

Prompt Function

Prompt box

This function gathers info from the user.

function prompter() {

    let promptValue = prompt('What is your name?', 'options');

    let promptOutput = document.getElementById('prompt-value');
    promptOutput.innerHTML = promptValue;
} <
button onclick = "prompter()" > Click to Prompt < /button>
                        		

The above code makes this button. Click it ot see the prompt box in action.

---Output here--

Arrow Functions

An Arrow Function is just a very easy syntax for creating anonymous functions. These functions treat this differently, as well. Basically, whatever their parent points to for this, so will the arrow function.

const myVar = (params) => logic that is automatically returned


 //	The result is automatically returned
 let doubleMe1 = (num1, num2) => num1 + num2;
 console.log(doubleMe1(7, 3)); //	RESULT: 10

 //	If there is only one parameter, parentheses are not needed
 let doubleMe2 = num => num * 2;
 console.log(doubleMe2(7)); //	RESULT: 14

 //	Can define return if you wish
 let doubleMe3 = num => {
     return num * 2
 };
 console.log(doubleMe3(7)); //	RESULT: 14

 //	For single lines, no brackets are needed. For multiline functions, { } need to be used.
 let largerFunct = num => {
     let newNum = num * 2;
     newNum = newNum * 100;
 };
 console.log(largerFunct(7)); //	RESULT: 1400
                        

One Reply to “Functions in JavaScript”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

q
↑ Back to Top