Javascript function return undefined

return

The return statement ends function execution and specifies a value to be returned to the function caller.

Try it

Syntax

The expression whose value is to be returned. If omitted, undefined is returned.

Description

The return statement can only be used within function bodies. When a return statement is used in a function body, the execution of the function is stopped. The return statement has different effects when placed in different functions:

  • In a plain function, the call to that function evaluates to the return value.
  • In an async function, the produced promise is resolved with the returned value.
  • In a generator function, the produced generator object’s next() method returns < done: true, value: returnedValue >.
  • In an async generator function, the produced async generator object’s next() method returns a promise fulfilled with < done: true, value: returnedValue >.

If a return statement is executed within a try block, its finally block, if present, is first executed, before the value is actually returned.

Automatic semicolon insertion

The syntax forbids line terminators between the return keyword and the expression to be returned.

The code above is transformed by automatic semicolon insertion (ASI) into:

Читайте также:  Задать размеры кнопки css

This makes the function return undefined and the a + b expression is never evaluated. This may generate a warning in the console.

To avoid this problem (to prevent ASI), you could use parentheses:

Examples

Interrupt a function

A function immediately stops at the point where return is called.

function counter()  // Infinite loop for (let count = 1; ; count++)  console.log(`$count>A`); // Until 5 if (count === 5)  return; > console.log(`$count>B`); // Until 4 > console.log(`$count>C`); // Never appears > counter(); // Logs: // 1A // 1B // 2A // 2B // 3A // 3B // 4A // 4B // 5A 

Returning a function

See also the article about Closures.

function magic()  return function calc(x)  return x * 42; >; > const answer = magic(); answer(1337); // 56154 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jun 19, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

JavaScript Return Undefined

JavaScript Return Undefined

  1. undefined in JavaScript
  2. Scenarios That Return undefined as the Output
  3. Difference Between undefined and null
  4. Conclusion

JavaScript has fewer libraries or frameworks than other programming languages. null and undefined represent empty values in JavaScript.

To reduce the errors that occur along with undefined , it is a must to have a clear understanding of the reason for returning undefined . Let’s have a quick overview of undefined in JavaScript.

undefined in JavaScript

Among the six primitive types of JavaScript, undefined is a special type of primitive with its value as undefined. Simply the only value the undefined type has is undefined.

undefined is a variable of global scope that is a non-writable and non-configurable property. According to the ECMA specifications, the value undefined is returned when a variable has not been assigned a value.

//uninitialized variable  let letters; console.log(letters);  //non-existing array elements  let vowels = ['a', 'e']; console.log(vowels[3]);  //non-existing object properties  let flower = < name: 'Rose' >; console.log(flower.color); 
undefined undefined undefined 

As it seems in the output, the value undefined is returned when accessing an uninitialized variable, non-existing array elements or object properties. After running each code chunk separately, we can get three undefined outputs.

Let’s see the situations where JavaScript returns undefined and some best practices to resolve returning undefined .

Scenarios That Return undefined as the Output

Accessing an Uninitialized Variable

If we declare a variable without initializing a value, the variable will return undefined.

let letters; console.log(letters); 

As in the code chunk, none of the values is assigned to the declared variable letters . As you see in the output above, it returns undefined with the calling of the variable, but if we assign a value for the variable, it returns the value below.

let letters = 5; console.log(letters); 

Accessing a Non-Existing Property

In the case of accessing a non-existing property, undefined is returned instead of throwing an error. The below example proves that well.

let flower =   name: 'Rose' >; console.log(flower.color); 

Here the object property flower has one property as the name . But when accessing, we have called the color property, which is a non-existing property of that object.

As shown in the output, it returns the value undefined as the output.

As the best practice, we can check the property’s availability using the below syntax before accessing it. Then we can get rid of returning undefined as the output.

'propertyName' in objectName 
let flower =   name: 'Rose' >;  if('color' in flower)  console.log(flower.color); > 

Calling Function Parameters

When we call a function with fewer arguments instead of the defined number of arguments, it returns undefined as it doesn’t pass all arguments. Therefore, we have to call the function with the same number of arguments.

function multiply(a, b, c)   a;  b;  c;  return a * b; > console.log(multiply(5, 3)); 

It has assigned values for the a and b , 5 and 3 , respectively when calling the function with two arguments so that it returns 15 as the output after assigning those values.

The following code calls the same function with the same two values after altering the expression of the return statement to multiply a , b and c altogether.

function multiply(a, b, c)   a;  b;  c;  return a * b * c; > console.log(multiply(5, 3)); 

As shown in the output, it returns NaN instead of computational values. The reason for that appearing is as it doesn’t pass all arguments and the value for c remains undefined .

the return Statement of a Function

Another instance where the output returns as undefined are if any function doesn’t have a return statement or has a return statement without an expression nearby.

For example, let’s declare a function named sq_num that generates a square number according to the given input.

//doesn't have a return statement  function sq_num(x)   const result = x * x; > console.log(sq_num(2));  //return statement without an expression  function sq_num(x)   const result = x * x;  return; > console.log(sq_num(2)); 

We must declare the return statement and an expression mentioned in the below code to work this function sq_num as expected. Through that, we can get the computational result of the function as below.

function sq_num(x)   const result = x * x;  return result; > console.log(sq_num(2)); 

Accessing Out-Of-Bound Elements in Arrays

If we access elements not defined within the array, it can be considered as accessing out-of-bound elements. If such a situation occurs, the undefined value is returned.

const animals = ['elephant', 'tiger', 'monkey']; console.log(animals[5]); console.log(animals[-1]); 

In the same way, sparse arrays present the same problem. Sparse arrays are arrays with gaps and non-indexed elements.

When accessing the empty slots of the array, it also returns the value undefined.

const SparseArray = ['elephant', , 'monkey']; console.log(SparseArray); 
["elephant", undefined, "monkey"] 

Here the array SparseArray is created with three elements, missing the second. As seen below, it returns undefined when accessing the second element.

const SparseArray = ['elephant', , 'monkey']; console.log(SparseArray[1]); 

Apart from the above scenarios, the value undefined is returned along with the void operator. Below are examples of how it returns undefined despite the evaluation result.

void 2; console.log(void(true)); 

Difference Between undefined and null

JavaScript has both null and undefined values representing empty values.

When a variable does not have an explicitly assigned value, JavaScript assigns it the primitive value of undefined. As the name implies, null is a primitive value representing an intentional absence of any other assigned value.

Using the typeof operator, we can see a distinction between null and undefined as below.

typeof undefined; typeof null; 

Overall, null indicates missing objects, while undefined is the value used in an uninitialized variable.

Conclusion

This article describes the occurrence of undefined along with the uninitialized variables, non-existing properties, out-of-bound indexes and the void operator.

Along with that discussed, some of the best practices can apply while using along with the examples. Apart, we looked at the difference between null and the defined values and their usage instances.

As a good practice, we should be responsible for reducing the occurrence of undefined by reducing the usage of uninitialized variables and sparse arrays.

Nimesha is a Full-stack Software Engineer for more than five years, he loves technology, as technology has the power to solve our many problems within just a minute. He have been contributing to various projects over the last 5+ years and working with almost all the so-called 03 tiers(DB, M-Tier, and Client). Recently, he has started working with DevOps technologies such as Azure administration, Kubernetes, Terraform automation, and Bash scripting as well.

Related Article — JavaScript Function

Источник

Оцените статью