JavaScript Functions

Subscribe to my newsletter and never miss my upcoming articles

What is a function?

  • A function is a group of code statements designed to perform a task. such group is a subprogram, that will always perform that specific task.

  • This functions or subprograms need to be called/invoked in order to be executed. they can be called or invoked by either external and internal code.

     Internal  - in cases such as recursion
     External - within the code of the program where the function lives o
                it can be called from other programs, as long as the function library
                is included in the calling program,
    
  • A function may or may not pass values to its main function body. Just like a program a function is composed of a sequence of code statements called the function body

  • In Javascript functions always return a value. if no return value is specified, the function will return undefined.

  • Because functions can have methods and properties just like anyother object they are first-class objects. one difference from other objects is that functions can be invoked/called.

Examples:

No passing values, No returning values

<!-- This function will print the word "Hello" -->
 function sayHello() {
    console.log("Hello");
}

 <!-- using Fat Arrow functions -->
 sayHola = () => { console.log("Hello");

calling / invoking functions

sayHello();
Returns:  "Hello"

sayHola();
Returns: "Hello"

Passing values

Let us pass a parameter. This is called a function's argument and it will always be passed by VALUE . if this argument is changed by the function it will not be reflected globaly, nor in the calling program or function.
An object reference is a value, but this an special case, because if a property of that object is changed by the body of the function, this change will be reflected globally.

<!-- name" is the parameter we are passing to the function -->
 function sayHello(name) {
    console.log("Hello");
}
<!--  using Fat Arrow functions -->
 sayHola = (name) => { console.log("Hello");

calling / invoking functions

sayHello("Anita");
Returns: "Hi Anita"

sayHola("Rosita");
Returns: "Hi Rosita"

Returning values

A returning value can be of any datatype:

  1. number
  2. string
  3. boolean
  4. array
  5. record objects

An example of a function returning each of the listed above, follows.

returning: number

Calling sum(arg1, arg2)

# adds arg1 and arg2, it returns the sum
function sum(num1, num2) {
    let total = num1 + num2;
    return total;
} 
let result = sum(20, 30);
console.log(`Result from adding 20 + 30 is ${result}`);

Returns:  "Result from adding 20 + 30 is **50**"

Calling square(arg1)

** takes num to the power of 2, and returns the result**
square = (num) => num * num;
console.log(`20 squared is ${square(20)}`);
 Returns: "20 squared is **400**"

returning: string

 # concatenates firstName and lastName into one string,
 # and returns the string
 function fullName(firstName, lastName)
{
      return lastName + ", " + lastName;
}

calling fullname(arg1, arg2)

 fullName("Sergio", "Rueda");

 Returns:  "Rueda, Rueda"

returning: boolean

# Checks if the value received is a number, if a number it returns 'true
# otherwise returns 'false'

function isNumber(value)
{
   return isNaN(value) ? false : true;
}

calling isNumber(arg1)

 isNumber('A');
 Returns: false

 isNumber(3);
Returns: true

returning: array

# takes a string argument and converts it to an array, and then it returns 
# the array.
function toArray(str)
{
  let array = str.split('');
  return array;
}

calling toArray(str)

let array1 = toArray("Sergio");
console.log(array1);
Returns: Array [  "S",  "e",  "r",  "g",  "i",  "o"]

Convert an array to string

# Here join() takes an array as input and returns a string
let Array =  [  "S",  "e",  "r",  "g",  "i",  "o"];
let str = Array.join('');
console.log(str); 
Returns: "Sergio"

Returning: Record Object

# let us write a function that will only create a record object
# and return it.

function returnARecord()
{
     let person = {
         firstName: 'sergio',
          lastName: 'Rueda',
         address:   '832 W. cuyler',
         city:      'Chicago',
         state:     'Illinois',
         country:   'USA'  
 }
 return (person);
}

calling returnARecord()

console.log(returnARecord());
Returns: 
Object {
  "address": "832 W. cuyler",
  "city": "Chicago",
  "country": "USA",
  "firstName": "sergio",
  "lastName": "Rueda",
  "state": "Illinois",
}
   let rec = returnARecord();
  console.log('Full name:  ' + rec.firstName + ', ' + rec.lastName);
  console.log(rec.address);
  console.log(rec.city + ', ' + rec.state + '  ' + rec.state);
  Returns:  
                "sergio , Rueda"
                "832 W. cuyler"
                "Chicago, Illinois  Illinois"

Please see live examples

More Javascript function examples

  1. convert any number in base 10 to binary
  2. format a date to YYYYMMDD
  3. reverse a string (recursion example)
  4. display an html list with a list of values (dynamicaly)
  5. display an html table with a list of values (dynamicaly)

Thanks for taking the time to read this article.

Let's Connect

next article: undecided.

No Comments Yet