Skip to content
the poor coder

Do functions in JavaScript necessarily return a value ?

Poor Man
Published
Reading time
1 min read
On this page

Do functions in JavaScript necessarily return a value?#

Yes, functions in JavaScript necessarily return a value but it can be undefined.

When a function is called, it may or may not return a value. If it does not have a return statement, the function returns undefined by default.

Example:#

Text

function greet(name) {
  console.log("Hello, " + name);
}

var result = greet("Raju");
console.log(result); // undefined
  

In the above example, the function greet() does not have a return statement. Therefore, it returns undefined by default. The variable result contains the returned value from the function which is undefined.

However, if a function has a return statement, it will always return a value. The returned value can be of any data type including objects and arrays.

Example:#

Text

function sum(a, b) {
  return a + b;
}

var result = sum(5, 10);
console.log(result); // 15
  

In the above example, the function sum() has a return statement which returns the sum of its two arguments. The variable result contains the returned value from the function which is 15.

So, to answer the question, functions in JavaScript necessarily return a value but it can be undefined if there is no explicit return statement.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC