Do functions in JavaScript necessarily return a value ?
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:
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:
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.