JavaScript Functions

JavaScript Functions

Functions are one of the major pillars of JavaScript. Many programming languages support various paradigms, the most well-known of which being Object-Oriented and Functional Programming. Although JavaScript can be both. Today in this blog, we will understand Functions in detail.

  • What is a Function?

  • Basics of Function in JavaScript

  • Parameters and Passing Arguments in Functions

  • Value-Returning Functions

  • Anatomy of a function

  • Arrow Functions

  • Parameters and Arguments in Arrow Function

  • Value-Returning Arrow Functions

  • Comparison between Regular and arrow functions

What is a Function?

✨ Functions are a block of code that is made to perform a particular task.

✨ To avoid repeating same code again and again all over places, you can use a function to wrap that code and reuse it.

✨ It helps you to divide a large program into small and manageable functions.

Basics of Function in JavaScript

To declare a function, you use the "function" keyword, followed by the function name, a list of parameters, and the function body as follows:

function helloVisitor() {}

As you can see, you can define it by using the function keyword, followed by a function name, open and close parenthesis, and curly braces.

But for now, if you put it on your code editor, we can't see anything on the browser console because we haven't put anything inside of it and we haven't invoked or called it yet.

Let's put some code and invoke it:

function  helloVisitor() {
   console.log('Hello, World');
   console.log('This is a blog');
}

 helloVisitor();

/**
   Output:
   Hello, World
   This is a blog
**/

✨ Simply use this syntax to call a function: yourFunctionName (). The output will appear in the browser's console once you've run it.

Anything you put inside the function will get executed if you call your created function.

But what if you want to receive some information from the user and then output it? Fortunately, functions can also accomplish that!

Parameters and Passing Arguments in Functions

First and foremost, what are parameters and arguments? I drew a diagram for you to make it easier:

Screenshot 2022-05-16 140948.jpg

Parameters is a name or variable that is declared in the function definition or, function header, so to speak.

Arguments is a real value that is passed in the function.

Note: Unlike in Java, JavaScript is a weak-typed language, meaning, you can pass any data in any type to it. Examples are:

  1. If you call helloVisitor({}), you will get Hello [object Object]

  2. If you call helloVisitor(1), you will get Hello 1

Now, the question is: What if we don't pass any value to it? What do you think would be the output?

Well, the parameter will become undefined because we don't define it in a function call.

helloVisitor(), will result in Hello undefined

In that case, we can also set the default value of the parameter by defining it upon declaration:

function helloVisitor(name = "Dhrumi") {
   console.log('Hello ' + name);
}

Now, if you only call helloVisitor(), the result will be Hello Dhrumi.

NOTE: You can override the value by simply providing an argument:

helloVisitor('Dhrumi') will result in Hello Dhrumi

Value-Returning Functions

We just developed a function that printed out the results in the previous instances, but what if we want our function's output to be stored in a variable as well?

Let's take an example: You are given a task to define a function that accepts two arguments. The first one is the price of the product, and the second one is the payment. The main goal of the function is to determine how much is the change for the customer.

function getChange(price, payment) {
  return payment - price;
}

And if we invoke it:

function getChange(price, payment) {
  return payment - price;
}

getChange(100, 150);

You can't see anything in the console because the function is not PRINTING OUT THE OUTPUT, but ONLY RETURNING it.

In that case, you simply do this: console.log(getChange(100, 150)) and the result is 50.

Anatomy of a function

Function name.png

Arrow Functions

Just like any other programming language, JavaScript is also adding awesome features to it. In 2015, ES6 or ECMAScript is released. It adds a new feature called Arrow Functions.

Arrow functions makes you the ability to create an anonymous function which is a function that does not have any name.

The basic syntax of declaring an arrow function is:

const arrowFunc = () => {}
// The anonymous function is `() => {}`

Note: functions can also be passed as a value of a variable.

Parameters and Arguments in Arrow Function

✨ For declaring parameters in arrow function, if it is one parameter, you can simply do this:

const arrowFunc = myParam => {}

where myParam is the parameter.

✨ If you have more than one parameter, you enclosed it in parenthesis and separate it with a comma:

const arrowFunc = (myFirstParam, mySecondParam, myThirdParam) => {}

Note: Invoking an arrow function is the same as a normal function declaration.

Value-Returning Arrow Functions

In arrow functions, the return keyword can also be removed:

// Normal function declaration
function helloVisitor(name) {
  return 'Hello ' + name;
}

// Arrow function declaration
const  helloVisitor= name => 'Hello ' + name;

As you can see, in a normal function declaration we need to explicitly put the return keyword while on the arrow function we can simply omit it. Through arrow functions, you can also make your function shorter.

NOTE: when you put curly braces after an => since it is now a block of code, you need to explicitly put the return keyword.

// Arrow function declaration
const helloVisitor= name => {
   'Hello ' + name;
}
// You will get undefined as a result since it isn't returning anything.

const helloVisitor = name => 'Hello ' + name;
/** You will get the desired result since it is not a block of code, 
 the return function is putted implicitly. */

Comparison between Regular and arrow functions

  • THIS Keyword :

Arrow functions, unlike normal functions, do not have their own this. 'This' in the case of an arrow function refers to the values of 'this' outside the arrow function , which remain constant throughout the function's lifecycle

image.png

  • Using NEW Keyword

Regular functions are constructible and callable . Regular functions can be invoked with the new keyword because they are constructible.

Arrow functions are only callable and not constructible, i.e. arrow functions can never be used as constructor functions. Hence, they can never be invoked with the new keyword.

image.png

  • No duplicate named parameters :

Arrow functions can never have duplicate named parameters, whether in strict or non-strict mode. Regular functions can have duplicate parameters in only non-strict mode.

image.png

  • Arrow functions are not hoisted.
helloVisitor()
const helloVisitor = () => {
    console.log('hello')
}

// Output:
// ReferenceError: Cannot access 'sayHello' before initialization

You've made it to an end 🎉🎉🎉

✨ That's it for now. Hope I have helped you through my blog. I regularly post threads on concepts of HTML CSS and JavaScript on Twitter.

Twitter handle : deetwts

If you like my content, you can support me here :

Buy me a coffee❤