Using Functions in JavaScript

Akshat Chaturvedi
Last Updated: May 13, 2022

Introduction

Just like any other language, JavaScript also has functions.

 

Don’t worry if you are new to JavaScript or studied it long before & want to revise this topic. I’ll cover all the critical points related to JavaScript functions in this blog post.

 

What is a function?

In general, a function is a block of code that we use to perform a specific task. In easier words, if we want to execute a piece of code n times with some slight changes, then instead of writing the code n times, we can simply put it inside a function and can call the function n times.

 

How to declare a function in JavaScript?

Declaring functions in JavaScript is super easy!

 

Unlike C++ or Java, we don’t have to specify the return type in JavaScript before the function.

 

The syntax of a simple “Hello World” function would look something like this:

 

function myFunction(){


    console.log(“Hello World”);


}

 

In JavaScript, we can use functions to perform a task when an event is triggered. We have different event listeners in JavaScript. For example, if we want to print “Hello World” on the console whenever the user clicks on a button, we can specify this function and the “click” event listener.

 

element.addEventListener("click", myFunction());

 

Whenever the user clicks on an element (could be a button), myFunction gets fired up, and we’ll see “Hello World” on the console.

 

Returning values from a function.

 

In JavaScript Functions, we don’t have to mention the return type in method definition that gives us the freedom to return any data type from the function without changing the method definition again and again.

 

  • Returning integer variable from the function.

 

function volume(length, breadth, height){
  
  let vol = length * breadth * height;


  let stringVol = "The volume of the given cuboid is: " + vol;


  return vol;
  
}
console.log(volume(2, 3, 4));    // Prints 24 on the console


// Volume of a cuboid with dimensions 2,4,8
// Assigning to a variable
let v = volume(2, 4, 8);
console.log(v);    // Prints 64 on the console

 

  • Returning string from the same function

 

function volume(length, breadth, height){
  
  let vol = length * breadth * height;


  let stringVol = "The volume of the given cuboid is: " + vol;


  return stringVol;
}
console.log(volume(2, 3, 4));    // Prints "The volume of the given cuboid is: 24"



// Volume of a cuboid with dimensions 2,4,8
// Assigning to a variable
let v = volume(2, 4, 8);
console.log(v);    // Prints "The volume of the given cuboid is: 64"

 

How to use parameters in functions?

Parameters are the variables passed to the function or the variable which gets defined while declaring a function. Parameters variables have their access limited to the scope of the function.

 

Function parameters are highly useful for the cases where we have to pass a value to the function—for instance, calculating the cube of a number.

 

In JavaScript, we don’t have to specify the datatype of the parameter.

 

function cube(number){


  console.log(number*number*number);


}
cube(2);        // Prints 8 on the console
cube(4);        // Prints 64 on the console

 

Arguments

In JavaScript, we have an array that stores all the parameters. The arguments array takes the parameters and stores them consecutively. The function can also access the parameters by making use of the array.

 

function myName(){


  console.log("My name is: " + arguments[0] + " " + arguments[1]);


}
myName("Akshat");
myName("Akshat", "Chaturvedi");

 

Output

My name is: Akshat undefined
My name is: Akshat Chaturvedi

 

Anonymous Functions

“Anonymous” Function as the name indicates these are the functions in javascript without a name. In JavaScript, we can assign a function to a variable and use the variable as a function.

 

We have to assign an anonymous function to a variable to use in the future.

 

let cube = function(x){
  
  return x * x * x;
  
}
console.log(cube(2));    // Prints 8 to the console

 

let showName = function(name){
  
  console.log(name + " Chaturvedi");
  
}


showName("Akshat");    // Prints Akshat Chaturvedi to the console

 

Inbuilt Functions in JavaScript

JavaScript has a whole range of different built-in functions available. To mention a few, I have explained below some common functions:

 

  1. charAt(index)

This function returns the character at the mentioned index in the string.

let language = "JavaScript";
console.log(language.charAt(1));    // prints a
console.log(language.charAt(4));    // prints S

 

  1. concat(string)

This function concatenates two strings into a single string.

let str1 = "JavaScript";
let str2 = " Language";


let str3 = str1.concat(str2);
console.log(str3);    // prints JavaScript Language

 

  1. length()

Returns the length of a string.

let str = “Hello World”;
console.log(str.length);    // prints 11

 

  1. strike()

Strikes through the given string.

let str = "Hello World";
console.log(str.strike());    // prints “<strike>Hello World</strike>”

 

The “<strike>Hello World</strike>” in HTML means “Hello World”

 

  1. Date()

The Date functions return today’s date and time of calling the function.

let date = Date();
console.log(date);


// Output: Fri Sep 24 2021 18:57:46 GMT+0000 (Coordinated Universal Time)

 

Frequently Asked Questions

 

1.What is JavaScript?

  • JavaScript is a programming language used for the web.
  • JavaScript is interpreted (line-by-line).
  • JS supports object-oriented scripting.
  • It is both front-end and back-end friendly.
  • JavaScript is used for web applications, mobile applications as well as game development.


2.Why is JavaScript used for Web Development?

JavaScript is used in web applications to make it suitable for the user to interact with the website. It gives the webpage special effects and dynamic properties. We also use JS for form validation purposes.


3.How is JavaScript different from Java?

JavaScript should not be confused with Java. These both are different in various ways:

  • Java requires the code to be compiled, but it is not in JavaScript since it is interpreted.
  • Java is a standalone language, whereas javascript works in coordination with HTML pages and sometimes CSS.
  • Java is strictly object-oriented, meaning that we cannot make programs without classes in Java, but JavaScript objects are prototype-based.


4.What is the use case of functions in JavaScript?

Javascript has a wide range of use cases. For instance, we can use functions to perform a task when an event is triggered. We have different event listeners in JavaScript like “click,” “mouseover,” “mouseout.”

 

This means that the function will get fired whenever we click on an element or bring the mouse over the element.

 

5. How to display the current date and time using JavaScript?

 

The function to display the current date is:

let date = new Date();
console.log("Date in DD/MM/YYYY format: "+ date.getDate() + "/" + date.getMonth() + "/" + date.getFullYear());


// OUTPUT: Date in DD/MM/YYYY format: 24/8/2021

 

The function to display the current time is:

let date = new Date();
console.log("Time in HH:MM:SS format: "+ date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds());


// OUTPUT: Time in HH:MM:SS format: 19:46:42

 

Key Takeaways

 

Functions are an essential part of a programming language. It makes coding things so much easier & also the code looks more compact and neat.

 

In this blog post, we saw how to use functions in the JavaScript scripting language.

 

Suppose you are preparing for some web development interview or making a website based on JavaScript. In that case, you must know what functions are in JavaScript, how to use them, and what types of inbuilt functions are in JavaScript.

 

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think