Mastering JavaScript Functions: Everything you need to know...!

Mastering JavaScript Functions: Everything you need to know...!

A Comprehensive Guide to Mastering Functions

ยท

5 min read

Functions

Functions are fundamental building blocks in JavaScript.

A function is a set of instructions that performs a specific task. Functions are used to break down a program into smaller, reusable pieces.

A function consists of a sequence of statements known as the function body. Values can be passed to a function as parameters, and the function will return a value.

In JavaScript, functions are first-class citizens. What distinguishes them from other objects is that functions can be called.

Function Structure

Declaring a function

There are many ways to create functions in JavaScript.

  1. Function Declaration

  2. Function Expression

  3. Named Function Expression

  4. ES6+ Method Declaration (Class Methods)

Function Declaration

This is the most common and traditional way to define a function. Function declarations are hoisted, meaning they can be called before they are defined in the code.

const greet = function(name) {
  return `Hello, ${name}!`;
};
console.log(greet("Ramya")) // Output: Hello, Ramya

Function Expression

A function expression assigns an anonymous function (a function without a name) to a variable. Function expressions are not hoisted, so they cannot be called before they are defined.

const greet = function(name) {
  return `Hello, ${name}!`;
};

Named Function Expression

It is a feature in JavaScript that allows you to create an anonymous function with a named property. This can be useful when you want to create a reusable piece of code but don't want to pollute the global namespace by declaring it as a standalone function.

const multiply = function multiplyNumbers(a, b) {
  return a * b;
};
console.log(multiplyy(2, 4)); // Output: 8

ES6+ Method Declaration (Class Methods)

The function that belongs to an object or a class. In the context of classes, a method is a function that belongs to the class and can be called on instances of the class.

OOP's concepts will be covered later.

class Calculator {
  add(a, b) {
    return a + b;
  }
}

const myInstance = new Calculator();
console.log(myInstance.add(4, 6)); // Output: 10

Calling a function

To call a function write the function name followed by parenthesis and the arguments that you want to pass to the function.

If there is no parameter then write a blank parenthesis.

function hello() {
  console.log("Hello World!");
}
// Function call
hello();

/*
    OUTPUT

    Hello World!
*/

function parameter/arguments

function parameter

A function parameter is declared inside the parentheses (). A function parameter is used inside the function body.

function arguments

The actual values that are passed while calling a function.

  1. When the number of arguments is less than the parameters then the rest of the parameters will be undefined

  2. When the number of arguments is more than the parameters, the extra arguments will be ignored.

function fullName(firstname, lastname) {
  console.log(firstname + " " + lastname);
}
fullName("Stephen", "Hawking");
fullName("Stephen", "William", "Hawking");
fullName("Stephen");

/*
    OUTPUT

    Stephen Hawking
    Stephen William
    Stephen undefined
*/

function return

return keyword is used to return the values to the function call.

The function stops execution when reached to return statement even if there are more statements in the function after a return.

The return value can be stored in a variable.

function multiply(a, b) {
  return a * b;
}
var value = multiply(4, 6);
console.log("Multiplication of 2 numbers:",value);

/*
    OUTPUT

    Multiplication of 2 numbers: 24
*/

you can use a return statement without returning any value just to stop the execution of the function.

Using console.log() in the function doesn't mean it will return the value of the function. It will just print it in the console.

specifying the default value to the function parameter

function userLoginMessage(username = "user") {
    return `${username} just logged in`;
}
let result = userLoginMessage("Subramanyeshwara");
let result1 = userLoginMessage();
console.log(result);
console.log(result1);

/*
    OUTPUT

    Subramanyeshwara just logged in
    user just logged in
*/
function printValue(a=1, b) {
    console.log("a = " + a + " and b = " + b);
}

printValue();
printValue(7);
printValue(7, 3);

/*
    OUTPUT

    a = 1 and b = undefined
    a = 7 and b = undefined
    a = 7 and b = 3
*/

Passing multiple values to a function

Using the rest operator we can pass multiple values to the single parameter of the function.

function calculateCartPrice(...cartItems) {
    return cartItems;
}
let cartItems = calculateCartPrice(500, 700, 300, 900);
console.log(cartItems);
// We can also use rest operator after taking some values
function calculateCartPrice1(cartItems1, cartItems2, ...cartItemsN) {
    return cartItemsN;
}
let cartItems1 = calculateCartPrice1(500, 700, 300, 900);
console.log(cartItems1);

/*
    OUTPUT

    [ 500, 700, 300, 900 ]
    [ 300, 900 ]
*/

Passing Object into a function

const user = {
    userName: "K Subramanyeshwara",
    userAge: 26
}
function handleObject(anyObject) {
    // return `User name is ${anyObject.userName} and User age is ${anyObject.userAge}`;
    console.log(`User name is ${anyObject.userName} and User age is ${anyObject.userAge}`);
}
// let functionReturn = handleObject(user);
// console.log(functionReturn);
handleObject({
    userName: "Ramya",
    userAge: 31
});

/*
    OUTPUT

    User name is K Subramanyeshwara and User age is 26
    User name is Ramya and User age is 31
*/

Passing Array into a function

const studentScore = [87, 72, 95, 74, 91, 83];

function handleArray(anyArray) {
    return `Student score for 3rd subject is ${anyArray[2]}`;
}

// const functionReturn = handleArray(studentScore);
// console.log(functionReturn);
console.log(handleArray([67, 48, 98, 75]));

/*
    OUTPUT

    Student score for 3rd subject is 95
    Student score for 3rd subject is 98
*/

I'll be diving into Immediately Invoked Function Expressions (IIFE) and Arrow functions in my next blog. Stay tuned!

Conclusion

Mastering JavaScript functions is essential for any developer looking to build efficient and reusable code. You can write more modular and maintainable programs by understanding the various ways to declare, call, and utilize functions.

Functions in JavaScript are versatile and powerful, allowing for various ways to declare and use them, from traditional function declarations to modern ES6+ arrow functions and class methods.

Essential for developers to understand how to pass parameters, handle arguments, and return values.

Thank you for taking the time to read this article ๐Ÿ˜Š. I hope the article provided you with valuable insights. I would highly appreciate it if you took a moment to like ๐Ÿ‘, share your thoughts or feedback comment โœ๏ธ, and share ๐Ÿ” it.

You can also follow me for more content on CSS, Javascript, React, Git and other web Development topics.

Happy Learning...! โœŒ๏ธโœŒ๏ธโœŒ๏ธ

For Paid collaboration, please mail me at:

If you liked my content, Connect with me on,LinkedInGitHubTwitterInstagram

Did you find this article valuable?

Support K Subramanyeshwara by becoming a sponsor. Any amount is appreciated!

ย