Table of contents
Introduction
Hey folks, I hope that you must have read my Day 6 Article on #30DaysOfJs. In case, if you haven't then make sure you give it a read by clicking here.
Functions
What is a function? Before we start making functions, let's understand what function is and why we need function.
A function is a reusable block of code that is declared by a function keyword followed by a name, followed by parentheses (). Parentheses can take a parameter. If a function takes a parameter it will be called with argument. A function can also take a default parameter.
Some advantages of functions are:
Clean and easy to read
Reusable
Easy to test
Some of the ways to create functions are:
Declaration function
Expression function
Anonymous function
Arrow function
- Function Declaration: Below is an example of how to declare a function.
Syntax:
function functionName() {
// Code
}
functionName() // Calling function by its name with parentheses
- Function Without a Parameter and Return: Functions can also be declared without a parameter.
For Example 1:
// Function without parameter, a function which make a number square
function square() {
let num = 2
let sq = num * num
console.log(sq);
}
// 4
square()
// Function without parameter
function addTwoNumbers() {
let numOne = 10
let numTwo = 20
let sum = numOne + numTwo
console.log(sum);
}
addTwoNumbers() // A function has to be called by its name to be executed
For Example 2:
function printFullName (){
let firstName = 'Shivank'
let lastName = 'Kapur'
let space = ' '
let fullName = firstName + space + lastName
console.log(fullName);
}
printFullName() // Calling a function
- Function Returning Value: A function can also return values, if a function doesn't return values the value of the function is undefined.
For Example:
function printFullName (){
let firstName = 'Shivank'
let lastName = 'Kapur'
let space = ' '
let fullName = firstName + space + lastName
return fullName
}
console.log(printFullName());
- Function With a Parameter: In a function, we can pass different Data Types (Number, String, Boolean, Object, function) as a parameter.
// Function with one parameter
function functionName(parm1) {
// Code
}
functionName(parm1) // During calling or invoking one argument needed
function areaOfCircle(r) {
let area = Math.PI * r * r
return area
}
console.log(areaOfCircle(10)); // Should be called with one argument
function square(number) {
return number * number
}
console.log(square(10));
- Function With Two Parameters:
For Example:
// Function with two parameters
function functionName(parm1, parm2) {
// Code
}
functionName(parm1, parm2) // During calling or invoking two arguments needed
// Function without parameter doesn't take input, so lets make a function with parameters
function sumTwoNumbers(numOne, numTwo) {
let sum = numOne + numTwo
console.log(sum);
}
sumTwoNumbers(10, 20) // Calling functions
// If a function doesn't return it doesn't store data, so it should return
function sumTwoNumbers(numOne, numTwo) {
let sum = numOne + numTwo
return sum
}
console.log(sumTwoNumbers(10, 20));
function printFullName(firstName, lastName) {
return `${firstName} ${lastName}`
}
console.log(printFullName('Asabeneh', 'Yetayeh'));
- Function With Unlimited Number Of Parameters: Many times we don't know how many arguments to write in a function. Therefore, there are different ways of taking an unlimited number of arguments. Some of examples for function declaration and arrow function are:
- Unlimited Number Of Parameters In Regular Function:
Syntax:
// Let us access the arguments object
function sumAllNums() {
console.log(arguments);
}
// Arguments(4) [1, 2, 3, 4, callee: ƒ, Symbol(Symbol.iterator): ƒ]
sumAllNums(1, 2, 3, 4)
For Example:
// Function declaration
function sumAllNums() {
let sum = 0
for (let i = 0; i < arguments.length; i++) {
sum += arguments[i]
}
return sum
}
console.log(sumAllNums(1, 2, 3, 4)); // 10
console.log(sumAllNums(10, 20, 13, 40, 10)); // 93
console.log(sumAllNums(15, 20, 30, 25, 10, 33, 40)); // 173
- Unlimited Number Of Parameters In Arrow Function:
Syntax:
// Let us access the arguments object
const sumAllNums = (...args) => {
// console.log(arguments), arguments object not found in arrow function
// Instead we use a parameter followed by spread operator (...)
console.log(args);
}
// [1, 2, 3, 4]
sumAllNums(1, 2, 3, 4)
For Example:
// Function declaration
const sumAllNums = (...args) => {
let sum = 0
for (const element of args) {
sum += element
}
return sum
}
console.log(sumAllNums(1, 2, 3, 4)); // 10
console.log(sumAllNums(10, 20, 13, 40, 10)); // 93
console.log(sumAllNums(15, 20, 30, 25, 10, 33, 40)); // 173
- Anonymous Function:
Syntax:
const anonymousFun = function() {
console.log(
'I am an anonymous function and my value is stored in anonymousFun'
)
}
- Expression Function:
Syntax:
// Function expression
const square = function(n) {
return n * n
}
// 4
console.log(square(2));
- Self-Invoking Functions: These functions are anonymous functions that do not need to be called to return a value.
(function(n) {
console.log(n * n)
})(2) // 4, but instead of just printing if we want to return and store the data, we do as shown below
let squaredNum = (function(n) {
return n * n
})(10)
console.log(squaredNum);
- Arrow Functions: These are an alternative to write functions. However, function declaration and arrow function have some minor differences. The arrow function uses an arrow instead of a keyword function to declare a function.
For Example:
const changeToUpperCase = arr => {
const newArr = []
for (const element of arr) {
newArr.push(element.toUpperCase())
}
return newArr
}
const countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland'];
// ["FINLAND", "SWEDEN", "NORWAY", "DENMARK", "ICELAND"]
console.log(changeToUpperCase(countries));
- Function With Default Parameters: Sometimes we pass default parameters, when we invoke the function if we do not pass an argument then the default value will be used.
Syntax:
// Declaring a function
function functionName(param = value) {
// Code
}
// Calling function
functionName()
functionName(arg)
For Example 1:
function greetings(name = 'Shivank') {
let message = `${name}, welcome to 30 Days Of JavaScript!`
return message
}
console.log(greetings());
console.log(greetings('Kapur'));
For Example 2:
function calculateAge(birthYear, currentYear = 2019) {
let age = currentYear - birthYear
return age
}
console.log('Age: ', calculateAge(1819));
For Example 3:
function weightOfObject(mass, gravity = 9.81) {
let weight = mass * gravity + ' N' // The value has to be changed to string first
return weight
}
console.log('Weight of an object in Newton: ', weightOfObject(100)); // 9.81 gravity at the surface of Earth
console.log('Weight of an object in Newton: ', weightOfObject(100, 1.62)); // gravity at surface of Moon
Now, we'll write the above functions with the arrow functions.
Syntax:
// Declaring a function
const functionName = (param = value) => {
// Code
}
// Calling function
functionName()
functionName(arg)
For Example 1:
const greetings = (name = 'Shivank') => {
let message = name + ', welcome to 30 Days Of JavaScript!'
return message
}
console.log(greetings());
console.log(greetings('Kapur'));
For Example 2:
const calculateAge = (birthYear, currentYear = 2019) => currentYear - birthYear
console.log('Age: ', calculateAge(1819));
For Example 3:
const weightOfObject = (mass, gravity = 9.81) => mass * gravity + ' N'
console.log('Weight of an object in Newton: ', weightOfObject(100)); // 9.81 gravity at the surface of Earth
console.log('Weight of an object in Newton: ', weightOfObject(100, 1.62)); // gravity at surface of Moon
I hope that you must have found this article quite helpful. If yes, then do give a read to some of my other articles!
Who knows you might become a great programmer 🤔!