Functions in Javascript.

Functions in Javascript.

Β·

11 min read

Hello Everyone πŸ‘‹

I'm Akshay, in this article, we will be discussing functions in javascript, the topics we are going to cover are :

  • Functions
  • Functional Programming
  • Function statement and function expression
  • Pure function, first-class functions
  • Anonymous Functions, IIFE and many more

    Quick disclaimer 🚫

    The article is more focused on interview preparation or if you have few months of coding experience and want to dive deep into javascript functions, this is for you. If you are a newbie who is trying his hands on javascript, I am sorry, the article will help you to a certain extent but you will end up being confused more, than understanding the concepts

Let's go πŸš€ πŸš€ πŸš€

Before I jump in and start explaining the actual concepts, I want to explain a few basics which will help you understand the concept better

1) Programming Paradigms In Javascript.

A programming paradigm is a style, or β€œway,” of programming or Programming paradigms are a way to classify programming languages based on their features

Modern programming languages are categorized into two type

  1. Imperative (procedural programming)
  2. Declarative (Functional Programming)

Javacsript is a multi-paradigm Programming language JavaScript supports both object-oriented programming with prototypal inheritance as well as functional programming.

In this article, we will focus completely on Functional Programming part of the javascript

2) Expressions

An expression is a combination of operators, constants, and variables. An expression may consist of one or more operands, and zero or more operators to produce a value.

or in simple terms a fragment of code that has some value

Ex : x=7 or 3+4 etc :

3) Statements

A statement is a command that the programmer gives to the computer or giving a set of instructions to do a particular task

ex: console.log("Hello World!") or aValue++ (incrementing) etc :

Now that we have covered few basic terminologies, let's just start learning functions in javascript

4) What is a function?

Functions are one of the fundamental building blocks in JavaScript. A function in JavaScript is similar to a procedure a set of statements that performs a task or calculates a value, but 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. To use a function, you must define it somewhere in the scope from which you wish to call it.

function jsFunction () {
return `Hello there`
}
jsFunction()

The above snippet of code is a simple example of how we write a function in javascript We have written a special keyword Function followed by a variable to store the value of a function, followed by opening and closing brackets, and we added our code snippet into the curly brackets(Block).

On the very next line, we have invoked the function so that the function can execute whatever code present inside the block and we are returning a string from the function

Now that we have learned what a Function is, let's move further and discuss some of the important concepts related to functions

4) Function expression

In function expression, we treat the function like any other variable in javascript, we store the function as a value inside a variable, and we invoke the variable to call the function

const funVar = function () {
    return "hey"
}
funVar()

As you can see, the functional expression looks almost similar to a regular javascript function except it is treated as a value stored in a variable, Function expressions in JavaScript are not hoisted, unlike function declarations. You can't use function expressions before you create them.

if we do console.log(funVar) we will see

Ζ’ () {
    return "hey"
}

an anonymous function,(function with no name) which we will discuss in the coming section.

The function expression doesn't need to be anonymous, it can be a named function expression too, like below example

const funVar = function test() {
    return "hey"
}
console.log(funVar);

By this time you have realized that the named function expression is nothing but the functional expression with a name on it

🚫 Do not try to call test() outside the function, it will throw an error, it can only be accessed inside the function expression

Function expression plays a very crucial role during IIFE () or Anonymous function.

5) Function Statement

The above example where I described what functions are, that is an example for a simple functions statement also know Functional definition or Function declaration.

🚫 Function statement should always have some name, it cannot be an anonymous function.

For ex :

function() {
  return "Hey there!"
}

Uncaught SyntaxError: Function statements require a function name

Now we are going to discuss a very important topic

6) Functional Programming

Functional programming (also known as FP) is a process of writing an application or software by composing Pure functions avoiding Shared state, Mutable data and side effects. We will discuss these topics in detail in the coming section.

We read about Programming Paradigms , and FP is one among them, We follow the above principles while creating an FP

  • What are Shared state

Scope is a boundary or an area where we can access a particular variable or a function

A shared state is any object, functions, or variable that present in shared scope or a variable that is shared between multiple scores, objects are shared between scopes by adding properties to other objects but in FP we tend to avoid that because if you want to check the function's side effect, you might have to understand the entire history or all shared spaces where the object/variable has been used.

  • Mutable Data

All reference data types such as Arrays and objects(which is an object by the way) are more prone to mutability since their value is not stored by a variable inside the call stack, instead, they will be stored in memory heap and variable will have the reference to that memory location in a heap of memory

When you try to copy a reference data type, you copy their memory reference instead of their value, because of this if you make a duplicate copy of an array or object and update the data, then it will also update the original array/object

In Functional programming, you tend to not change any data other than the input/argument

  • SIde Effects

Below are the example of some side effects

  1. Logging to the console
  2. Writing to the screen
  3. Writing to a file
  4. Writing to the network
  5. Triggering any external process
  6. Calling any other functions with side-effects

In FP, our functions should not make any of these side effects

Now we will discuss one of the important topic and core fundamental of Functional programming

7) Pure function

We learned that in FP, we use pure functions while building an application but what exactly are pure functions?

A function which

  • Gives the same output for the same input no matter how many times it is repeated
  • Does not mutate/use any other variable or objects outside the function
  • Its output is not dependent on any other factor except the input
  • Does not produce any kinds of side effects

Is know an Pure Function

A dead giveaway that a function is impure is if it makes sense to call it without using its return value. For pure functions, that’s a loop.

Some benefits of pure functions

  • Since it is independent, it is immune to any bugs or error outside the function
  • Since it is not using any other data, we can test it then and there.
  • It is very easy to refractor, move around and scale since you know modifying that particular function will not after any other data.

Some examples of impure functions

Math.random(); // => 0.4011148700956255
Math.random(); // => 0.8533405303023756
Math.random(); // => 0.3550692005082965

As the name itself suggest it generates a random number, so it's not a pure function since it generates random output every time it is being called

const time = () => new Date().toLocaleTimeString();
time(); // => "5:15:45 PM"

Again, since it is generating a new second every time, it does not qualify for Pure function.

8) First class function

A programming language is said to have first-class functions if their function can be used like any other variable

for ex:-

  • Function can be stored inside a variable as the value
let test = function () {
 console.log("Hello");
}

Here we are creating a function as a normal value and if we do console.log(test) we will get

Ζ’ () {
 console.log("Hello");
}
  • Function can be passed as an argument

    function main(fn) {
    return fn()
    }
    let test = function () {
    console.log("Hello");
    }
    main(test)
    

    Here we not only storing the test function inside a variable but we also passing the test as an argument

  • Function can be returned from any function

function main(fn) {
  return fn
}
let test = function () {
 console.log("Hello");
}
let returnedFun = main(test)

console.log(returnedFun);

//==output
 Ζ’ () {
 console.log("Hello");
}

Here we are returning a function as a variable.

7) Anonymous function

As we discussed above anonymous functions are the function which does not have any name on it and I also said that only functional statement can have an anonymous function and not functional express,

let test = function () {

}

Above is an example of a functional expression, here we are storing an Anonymous function as a value inside a variable called test.

Where anonymous functions are used? :

  • Anonymous functions are used as callback functions
  • Anonymous functions are used in Immediately invoked function expression

8) CallBack Functions

Callback functions are named or anonymous functions we pass inside a function as an argument so that it can be invoked after some time to some kind of routine or action

let arr = [1, 2, 3, 4, 5]

let anonfun = function test2(ele) {
  return ele===1
}
let filterfun = arr.filter(anonfun)

console.log(filterfun);

Above we are using the Filter method an Higher-order function (which we will cover in the coming section), and inside that filter function we are passing one more named functional statement, and that is called callBack function

As I said above we sometimes want to use or invoke a function asynchronously / after some time, A good example is the callback functions executed inside a .then() block chained onto the end of a promise after that promise fulfills or rejects. This structure is used in many modern web APIs, such as fetch().

8) Immediately Invoked Function Expression (also know as IIFE)

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.

Before I explain what IIFE is I would like you to show a code snippet of it

(function () {
  console.log("hey");
})()

As you can see above, I have written the Function keyword followed by writing a normal piece of code inside it which is lexically enclosed by a grouping operator ( ) and immediately invoked function expression( ) through which the JavaScript engine will directly interpret the function.

so IIFE is a function that is invoked as soon as the interpreter reads that point and it does not have to be explicitly invoked to call the function.

  • Uses of IIFE

  • When Let and Const was not introduced earlier, writing a code completely using Var was pretty difficult since it can be over-ridden because Var has functional as well as Global scope. to avoid that, Devs used to create an IIFE to make the var as function block so that it won't be modified by other Devs.

  • I use it inside UseEffect of my react application whenever I want to make an API call and since UseEffect cannot be async in nature I used to write something like this

useEffect(() => {
  (async () => {
    try {
      const data = await axios.get(`https://getMeARandomPost.com`);
      console.log(data);
    } catch (error) {
      console.log(error);
    }
  })();
},[]);

It is pretty easy and cleaner than defining a new function and invoking it.

8) Higher Order function

Higher order functions are functions that operate on other functions, either by taking them as arguments or by returning them. In simple words, A Higher-Order function is a function that receives a function as an argument or returns the function as output.

Ex: Map, find, filter, some, and foreEach are some examples of higher-order function

let newArr = [1, 2, 3, 4, 5]

let evenNum = newArr.filter((ele, index) => {
  if (ele % 2 == 0) {
    return ele
  }
})
console.log(evenNum);
output=>[ 2, 4 ]

In the above example, I have an array of numbers from 1 to 5 and I am trying to print even numbers from it. I am using a Filter functional (higher-order function) which will be operated on each number and returns a new array that satisfies the condition. as you can see, I have added anonymous callback functions inside the .Filter function as an argument.

So here Filter is a higher-order function since it is accepting a function as an argument

That's all folks for today's topic, hope you folks were able to understand the javascript function a level deeper and more clear.

Thank you. πŸ‘‹ πŸ‘‹

Β