Sign in
Log inSign up
Understanding Basics of Javascript Functions

Understanding Basics of Javascript Functions

Nads's photo
Nads
·Jan 8, 2022·

6 min read

Introduction

JavaScript is a widely used and well-known programming language. Many programming languages offer different paradigms and are commonly known to them are Object-Oriented and Functional Programming. Javascript can be both, but the most widespread approach of it is the Functional paradigm.

You can check the definition here: Functional Paradigm Definition by Wikipedia

In my own definition, unlike in the OOP approach, functional programming is not entity or object-based. This makes your app organized through functions. The protagonist is the FUNCTION. Functional programming also offers the ability to create a pure function, meaning, when you give the same input, it must achieve the exact and same result without having side effects in your program which is the main cause of bugs.

Who loves Bugs? No one! 😒😒😒

What is a Function?

Functions are a block of code that is made to perform a particular task. It can also get an input, process it, and give you the desired result.

Basics of Function in JavaScript

Here's one of the basic syntaxes to define a function in JavaScript.

function sayHello() {}

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 sayHello() {
   console.log('Hello, World');
   console.log('This is my first blog');
}

sayHello();
/**
   Output:
   Hello, World
   This is my first blog
*/

To invoke a function, just simply follow this syntax yourFunctionName(). Once you invoke it, you will see the output in the browser's console.

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

But what if you want to get some data from the user and output it? Well, fortunately, functions can do that too!

Parameters and Passing Arguments in Functions

First of all, what in the hell is Parameters and Arguments? To make it simple I made a diagram for you: Functions in JS Blog Photo.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.

Just like in any debate, if the topic is about trees, your arguments should be related to trees.

Alright! Moving on! Here's the new definition of our sayHello() function:

function sayHello(name) {
   console.log('Hello ' + name);
}

sayHello('John');

/**
Output:
Hello John
*/

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

  • If you call sayHello({}), you will get Hello [object Object]

  • If you call sayHello(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.

sayHello(), will result in Hello undefined

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

function sayHello(name = "John") {
   console.log('Hello ' + name);
}

Now, if you only call sayHello(), the result will be Hello John.

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

sayHello('Marites') will result in `Hello Marites

Value-Returning Functions

In our previous examples, we only created a function that only printed out the results, but what if we want the result of our function to store in a variable too?

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.

You might also ask, what's the point of making a function as a Value-Returning function? Well, one of the two most cases of it is you can make it as a value of a variable, and you can pass it as an argument to a function.

Imagine you're making a function that will print a receipt:

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

function printReceipt(price, payment, change) {

  console.log('Receipt\nStore: Yike Store');
  console.log('--------');
  console.log('Price: ' + price);
  console.log('Payment: ' + payment);
  console.log('Change: ' + change);
}

let price = 100;
let payment = 150;
let change = getChange(100, 150);

printReceipt(price, payment, change)
// or printReceipt(price, payment, getChange(100, 150));

As you can see, the code is much better than populating a function with another function.

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.

Examples of it are in the setTimeout function:

setTimeout(() => {
    console.log('I dropped the bomb!');
}, 3000)

As you can see we don't need any name for the function.

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 sayHello(name) {
  return 'Hello ' + name;
}

// Arrow function declaration
const sayHello = 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 sayHello = name => {
   'Hello ' + name;
}
// You will get undefined as a result since it isn't returning anything.

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

Be Careful

Arrow functions are not hoisted.

Example:

sayHello()
const sayHello = () => {
    console.log('hello')
}

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

unlike in normal function declaration

sayHello()

function sayHello() {
    console.log('hello')
}
// Output:
// hello

To avoid having an error like in the example above, one thing that I would recommend is always to declare your functions before using them.

You've reached the end! 🎉🎉🎉

I hope you learned some of the basics of Javascript Functions in this blog. This is my first blog so yeah, I'm proud to myself! ♥🥰

Here's my socials: Twitter LinkedIn Github