Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is a function?
3.
How to declare a function in JavaScript?
4.
Returning values from a function.
5.
How to use parameters in functions?
6.
Arguments
7.
Anonymous Functions
8.
Inbuilt Functions in JavaScript
8.1.
charAt(index)
8.2.
concat(string)
8.3.
length()
8.4.
strike()
8.5.
Date()
9.
Frequently Asked Questions
9.1.
What is JavaScript?
9.2.
Why is JavaScript used for Web Development?
9.3.
What is the use case of functions in JavaScript?
10.
Conclusion
Last Updated: Mar 27, 2024
Medium

Javascript Function

Author Rinki Deka
0 upvote

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.

Javascript Function

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.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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. To check try it on an online javascript compiler.

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("Rinki");
myName("Rinki", "Deka");

 

Output

My name is: Rinki undefined
My name is: Rinki Deka

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 + "Deka");
}

showName("Rinki");    // Prints Rinki Deka 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:

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

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

length()

Returns the length of a string.

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

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”

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)


Must Read Fibonacci Series in JavaScript

Frequently Asked Questions

What is JavaScript?

JavaScript is a programming language used for the web. It is interpreted (line-by-line) and it supports object-oriented scripting. JavaScript is used for web applications, mobile applications as well as game development.

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.

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.

Conclusion

In this blog post, we saw how to use functions in the JavaScript scripting language. Functions are an essential part of a programming language. It makes coding things so much easier & also the code looks more compact and neat.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Previous article
Javascript Void 0
Next article
Javascript Events
Live masterclass