Day 7. Functions

header image TIL

Functions

  • A function is a reusable block of code or programming statements, designed to perform a certain task. A function should take some input and return an output where there is some obvious relationship between the input and the output.

  • It is declared by function keyword, the name of the function, a list of parameters in parentheses, and statements in curly brackets.

  • Parentheses() can take a parameter, and if a function takes a parameter, it will be called with argument.

  • To store a data to a function, a function has to return certain data types. The return statement specifies the value returned by the function.

  • To get the value, we ‘call’ or ‘invoke’ a function.


Function Declaration

//declaring a function without a parameter
function functionName () {
  //code goes here
}
functionName()  //calling function by its name and with parentheses


I can also set a variable and assign it to a function. To execute the function, I just have to call the variable name with parameters. The variable will act like a function.

let a = function(firstName, lastName) {
  console.log(firstName + ' ' + lastName);
}

a('Ramona', 'Doe');
// Ramona Doe


1. Function without a parameter and return

Function can be declared without a parameter like below. A function has to be called by its name to be executed.

function square() {
  let num = 2;
  let sq = num * num;
  console.log(sq);
}

square()  //4

function printFullName() {
  let firstName = 'Jane';
  let lastName = 'Doe';
  let space = ' ';
  let fullName = firstName + space + lastName;
  console.log(fullName);
}
printFullName()  //Jane Doe


2. Function returning value

Function can return values. If a function doesn’t return values, the value of the function is undefined. From now on, I return value to a function instead of printing it(console.log()).

function printFullName() {
  let firstName = 'Jane';
  let lastName = 'Doe';
  let space = ' ';
  let fullName = firstName + space + lastName;
  return fullName;
}

console.log(printFullName());  //Jane Doe


3. Function with a parameter

I can pass different data types as a parameter in a function. The data types could be number, string, boolean, object, or function.

function functionName(parm1) {
  //code goes here
}
functionName(parm1)  //one argument is needed to call the function


function areaOfCircle(r) {
  let area = Math.PI * r * r;
  return area;
}

console.log(areaOfCircle(10));  //the argument is needed

I wasn’t sure about the difference between parameters and arguments, so I looked up the document.

Function parameters are the names listed in the function’s definition.
Function arguments are the real values passed to the function.


4. Function with two parameters

function functionName(parm1, parm2) {
  //code goes here
}
functionName(parm1, parm2);  //two arguments are needed to call the function


function sumTwoNumbers(numOne, numTwo) {
  let sum = numOne + numTwo;
  console.log(sum);
}
sumTwoNumbers(10, 20);  //30

function sumTwoNumbers(numOne, numTwo) {
  let sum = numOne + numTwo;
  return sum;
}

console.log(sumTwoNumbers(2, 9));  //11
  • A function without parameter doesn’t take input.
  • If a function doesn’t return, it doesn’t store data, so it should return.


function printFullName(firstName, lastName) {
  return `${firstName} ${lastName}`;
}

printFullName('Jane', 'Doe');  //'Jane Doe'


5. Function with many parameters

function functionName(parm1, parm2, parm3, ...) {
  //code goes here
}
functionName(parm1, parm2, parm3...);
function sumArrayValues(arr) {
  let sum = 0;
  for (let i = 0; i < arr.length; i++) {
    sum = sum + arr[i];
  }
  return sum;
}

const numbers = [1, 2, 3, 4, 5];
console.log(sumArrayValues(numbers));

The code above takes an array as a parameter and adds all the elements of the array.


const areaOfCircle = (radius) => {
  let area = Math.PI * radius * radius;
  return area;
}

console.log(areaOfCircle(10));

This has a slightly different style of declaring a function. I guess it’s an arrow function, which I’ll get to know down below. But it seems quite obvious that the areaOfCircle is a function and takes radius as a parameter.


6. Function with unlimited number of parameters

Sometimes I don’t know how many arguments that are going to be passed by the user. The function with unlimited number of parameters is used here.

Declaring such functions is different in regular function declaration and arrow function.

  • Unlimited number of parameters in regular function

A function declaration provides a function-scoped arguments array like object. (Scope means an accessible range.) Anything I pass as argument in the function can be accessed from arguments object inside the functions.

//accessing the arguments object
function sumAllNums() {
  console.log(arguments);
}
sumAllNums(1, 2, 3, 4);
//Arguments(4) [1, 2, 3, 4, callee: ƒ, Symbol(Symbol.iterator): ƒ]
//function declaration
function sumAllNums() {
  let sum = 0;
  for (let i = 0; i < arguments.length; i++) {
    sum += arguments[i];
  }
  return sum;
}

console.log(sumAllNums(10, 20, 30, 40));  //100

I didn’t fully get the idea, so I changed the arguments into somthing like arg and it didn’t work. Looking up the document, I found out there are something called ‘the arguments object’.

I can refer to a function’s arguments inside that function by using its arguments object. It has indexes that start from zero, like an array(it’s array-like, not an array). Each argument can be set or reassigned. Take time to read the document as it has a lot of information about the arguments object!


  • Unlimited number of parameters in arrow function

Arrow function does not have the function-scoped arguments object. To implement a function which takes unlimited number of arguments in an arrow function, I can use spread operator(...) followed by any parameter name. Anything I passed as argument in the function can be accessed as array in the arrow function.

//accessing the arguments object
const sumAllNums = (...args) => {
  console.log(args);
}
sumAllNums(1, 2, 3, 4);  //(4) [1, 2, 3, 4]

In the upper code, I used spread operator(...) in front of the arguments’ name instead of just putting arguments. Also, it seems that an arrow function is declared by const, not the function keyword.

Arguments object is not found in arrow function.

//function declaration
const sumAllNums = (...args) => {
  let sum = 0;
  for (const element of args) {
    sum += element;
  }
  return sum;
}

console.log(1, 2, 3, 4);  //10


7. Anonymous Function

Anonymous function is a function without a name, which is declared without any identifier. Only the function keyword is used to declare an anonymous function. Here’s some articles about anonymous functions.

function() {
  //code goes here
}
const anonymousFun = function() {
  console.log('I am an anonymous function and my value is stored in anonymousFun');
}


8. Expression Function

Expression functions are anonymous functions, after I create a function without a name and assign it to a variable. To return a value, I should call the variable.

const square = function(n) {
  return n * n;
}

console.log(square(2));  //4


9. Self Invoking Functions

Self invoking functions are anonymous functions which do not need to be calleed(or invoked) to return a value.

(function(n) {
  console.log(n * n);
})(2)  //4

let squaredNum = (function(n) {
  return n * n;
})(10);

console.log(squaredNum);

Putting only the anonymous function will only print out the data, not storing the value. To return the value and store the data, I have to declare another variable. The returned value will then be stored in the new variable.


10. Arrow Function

Arrow function is another way of writing a function. To declare a function, arrow function uses arrow, instead of function keyword.

//normal(declaration function)
function square(n) {
  return n * n;
}

console.log(square(2));  //4

//arrow function
const square = n => {
  return n * n;
}

console.log(square(2));  //4

//arrow function - if there's only one line in the code
const square = n => n * n;

console.log(square(2));  //4


If the function has only the return statement, I can explicitly return it like below.

const printFullName = (firstName, lastName) => {
  return `${firstName} ${lastName}`;
}

//explicit return
const printFullName = (firstName, lastName) => `${firstName} ${lastName}`;

console.log(printFullName('Jane', 'Doe'));  //Jane Doe


11. Function with default parameters

When I invoke the function, and if I don’t pass an argument, the default value will be used. I can pass the default values to parameters. Both function declaration and arrow function can have a default value(or values).

//function declaration
function functionName(param = value) {
  //code goes here
}

//calling the function
functionName();
functionName(arg);
function greetings(name = 'Paul') {
  let message = `${name}, welcome!`;
  return message;
}

console.log(greetings());  //Paul, welcome!
console.log(greetings('Jane'));  //Jane, welcome!


With arrow functions:

//function declaration
const functionName = (param = value) => {
  //code goes here
}

//calling the function
functionName()
functionName(arg);
const greetings = (name = 'Paul') => {
  let message = name + ', welcome!';
  return message;
}

greetings()
greetings(('Amy'));


Leave a comment