AI Creations

completion percent

Javascript Loops and Functions

Get Unstuck

Assignment with a Returned Value

If you'll recall from our discussion about Storing Values with the Assignment Operator , everything to the right of the equal sign is resolved before the value is assigned. This means we can take the return value of a function and assign it to a variable.

Assume we have pre-defined a function sum that adds two numbers together, then:

will call the sum function, which returns a value of 17 and assigns it to the ourSum variable.

Home » JavaScript Tutorial » Returning Multiple Values from a Function

Returning Multiple Values from a Function

Summary : in this tutorial, you will learn to define JavaScript functions that return multiple values.

JavaScript functions can return a single value. To return multiple values from a function, you can pack the return values as elements of an array or as properties of an object .

Returning multiple values from a function using an array

Suppose the following getNames() function retrieves the first name and last name from a database in the backend or from the result of a third-party API call and returns them as elements of an array:

The following shows how to get the return value from the getNames() function:

Because the names variable is an array, you can reference its elements using the square brackets, like this:

In ES6, you can use the destructuring assignment syntax to unpack values from an array more intuitively, like this:

In this code, the firstName and lastName variables will take the first and second elements of the return array.

Returning multiple values from an function using an object

If you want to assign a name to each returned value to make it more readable and easier to maintain, you can use an object :

Since the names of the properties are the same as the variables, you can shorten it using the object literal syntax extensions in ES6 as follows:

And you can get the return value as an object like this:

If you want to unpack properties from an object, you can use the object destructuring syntax as follows:

  • JavaScript doesn’t support functions that return multiple values. However, you can wrap multiple values into an array or an object and return the array or the object.
  • Use destructuring assignment syntax to unpack values from the array, or properties from objects.

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

What is the benefit of having the assignment operator return a value?

I'm developing a language which I intend to replace both Javascript and PHP. (I can't see any problem with this. It's not like either of these languages have a large install base.)

One of the things I wanted to change was to turn the assignment operator into an assignment command, removing the ability to make use of the returned value.

I know that this would mean that those one-line functions that C people love so much would no longer work. I figured (with little evidence beyond my personal experience) that the vast majority of times this happened, it was really intended to be comparison operation.

Or is it? Are there any practical uses of the assignment operator's return value that could not be trivially rewritten? (For any language that has such a concept.)

  • language-agnostic

billpg's user avatar

  • 12 JS and PHP do not have a large "install base"? –  mhr Commented Feb 13, 2014 at 12:33
  • 47 @mri I suspect sarcasm. –  Andy Hunt Commented Feb 13, 2014 at 12:41
  • 12 The only useful case I can remember is while((x = getValue()) != null) {} . Replacements will be uglier since you'll need to either use break or repeat the x = getValue assignment. –  CodesInChaos Commented Feb 13, 2014 at 13:04
  • 12 @mri Ooh no, I hear those two languages are just trivial things without any significant investment at all. Once the few people who insist on using JS see my language, they will switch over to mine and never have to write === again. I'm equally sure the browser makers will immediately roll out an update that includes my language alongside JS. :) –  billpg Commented Feb 13, 2014 at 14:58
  • 4 I would suggest to you that if your intention is to enhance an existing language and you intend it to be adopted widely then 100% backwards compatibility with the existing language is good. See TypeScript as an exemplar. If your intention is to provide a better alternative to an existing language then you have a much harder problem. A new language has to solve an existing realistic problem much much better than the existing language in order to pay for the cost of switching. Learning a language is an investment and it needs to pay off. –  Eric Lippert Commented Feb 13, 2014 at 18:57

9 Answers 9

Technically, some syntactic sugar can be worth keeping even if it can trivially be replaced, if it improves readability of some common operation. But assignment-as-expression does not fall under that. The danger of typo-ing it in place of a comparison means it's rarely used (sometimes even prohibited by style guides) and provokes a double take whenever it is used. In other words, the readability benefits are small in number and magnitude.

A look at existing languages that do this may be worthwhile.

  • Java and C# keep assignment an expression but remove the pitfall you mention by requiring conditions to evaluate to booleans. This mostly seems to work well, though people occasionally complain that this disallows conditions like if (x) in place of if (x != null) or if (x != 0) depending on the type of x .
  • Python makes assignment a proper statement instead of an expression. Proposals for changing this occasionally reach the python-ideas mailing list, but my subjective impression is that this happens more rarely and generates less noise each time compared to other "missing" features like do-while loops, switch statements, multi-line lambdas, etc.

However, Python allows one special case, assigning to multiple names at once: a = b = c . This is considered a statement equivalent to b = c; a = b , and it's occasionally used, so it may be worth adding to your language as well (but I wouldn't sweat it, since this addition should be backwards-compatible).

  • 5 +1 for bringing up a = b = c which the other answers do not really bring up. –  Leo Commented Feb 13, 2014 at 15:53
  • 6 A third resolution is to use a different symbol for assignment. Pascal uses := for assignment. –  Brian Commented Feb 13, 2014 at 19:08
  • 6 @Brian: Indeed, as does C#. = is assignment, == is comparison. –  Marjan Venema Commented Feb 13, 2014 at 19:47
  • 3 In C#, something like if (a = true) will throw a C4706 warning ( The test value in a conditional expression was the result of an assignment. ). GCC with C will likewise throw a warning: suggest parentheses around assignment used as truth value [-Wparentheses] . Those warnings can be silenced with an extra set of parentheses, but they are there to encourage explicitly indicating the assignment was intentional. –  Bob Commented Feb 13, 2014 at 22:27
  • 2 @delnan Just a somewhat generic comment, but it was sparked by "remove the pitfall you mention by requiring conditions to evaluate to booleans" - a = true does evaluate to a Boolean and is therefore not an error, but it also raises a related warning in C#. –  Bob Commented Feb 13, 2014 at 23:48
Are there any practical uses of the assignment operator's return value that could not be trivially rewritten?

Generally speaking, no. The idea of having the value of an assignment expression be the value that was assigned means that we have an expression which may be used for both its side effect and its value , and that is considered by many to be confusing.

Common usages are typically to make expressions compact:

has the semantics in C# of "convert z to the type of y, assign the converted value to y, the converted value is the value of the expression, convert that to the type of x, assign to x".

But we are already in the realm of impertative side effects in a statement context, so there's really very little compelling benefit to that over

Similarly with

being a shorthand for

Again, in the original code we are using an expression both for its side effects and its value, and we are making a statement that has two side effects instead of one. Both are smelly; try to have one side effect per statement, and use expressions for their values, not for their side effects.

I'm developing a language which I intend to replace both Javascript and PHP.

If you really want to be bold and emphasize that assignment is a statement and not an equality, then my advice is: make it clearly an assignment statement .

There, done. Or

or even better:

Or even better still

There's absolutely no way that any of those are going to be confused with x == 1 .

Eric Lippert's user avatar

  • 1 Is the world ready for non-ASCII Unicode symbols in programming languages? –  billpg Commented Feb 14, 2014 at 11:25
  • As much as I would love what you suggest, one of my goals is that most "well written" JavaScript can be ported over with little or no modification. –  billpg Commented Feb 14, 2014 at 11:44
  • 2 @billpg: Is the world ready ? I don't know -- was the world ready for APL in 1964, decades before the invention of Unicode? Here's a program in APL that picks a random permutation of six numbers out of the first 40: x[⍋x←6?40] APL required its own special keyboard, but it was a pretty successful language. –  Eric Lippert Commented Feb 14, 2014 at 15:17
  • @billpg: Macintosh Programmer's Workshop used non-ASCII symbols for things like regex tags or redirection of stderr. On the other hand, MPW had the advantage that the Macintosh made it easy to type non-ASCII characters. I must confess some puzzlement as to why the US keyboard driver doesn't provide any decent means of typing any non-ASCII characters. Not only does Alt-number entry require looking up character codes--in many applications it doesn't even work. –  supercat Commented Feb 14, 2014 at 18:20
  • Hm, why would one prefer to assign "to the right" like a+b*c --> x ? This looks strange to me. –  Ruslan Commented Aug 21, 2015 at 10:49

Many languages do choose the route of making assignment a statement rather than an expression, including Python:

and Golang:

Other languages don't have assignment, but rather scoped bindings, e.g. OCaml:

However, let is an expression itself.

The advantage of allowing assignment is that we can directly check the return value of a function inside the conditional, e.g. in this Perl snippet:

Perl additionally scopes the declaration to that conditional only, which makes it very useful. It will also warn if you assign inside a conditional without declaring a new variable there – if ($foo = $bar) will warn, if (my $foo = $bar) will not.

Making the assignment in another statement is usually sufficient, but can bring scoping problems:

Golang heavily relies on return values for error checking. It therefore allows a conditional to take an initialization statement:

Other languages use a type system to disallow non-boolean expressions inside a conditional:

Of course that fails when using a function that returns a boolean.

We now have seen different mechanisms to defend against accidental assignment:

  • Disallow assignment as an expression
  • Use static type checking
  • Assignment doesn't exist, we only have let bindings
  • Allow an initialization statement, disallow assignment otherwise
  • Disallow assignment inside a conditional without declaration

I've ranked them in order of ascending preference – assignments inside expressions can be useful (and it's simple to circumvent Python's problems by having an explicit declaration syntax, and a different named argument syntax). But it's ok to disallow them, as there are many other options to the same effect.

Bug-free code is more important than terse code.

amon's user avatar

  • +1 for "Disallow assignment as an expression". The use-cases for assignment-as-an-expression don't justify the potential for bugs and readability issues. –  poke Commented Feb 14, 2014 at 17:00

You said "I figured (with little evidence beyond my personal experience) that the vast majority of times this happened, it was really intended to be comparison operation."

Why not FIX THE PROBLEM?

Instead of = for assignment and == for equality test, why not use := for assignment and = (or even ==) for equality?

If you want to make it harder for the programmer to mistake assignment for equality, then make it harder.

At the same time, if you REALLY wanted to fix the problem, you would remove the C crock that claimed booleans were just integers with predefined symbolic sugar names. Make them a different type altogether. Then, instead of saying

you force the programmer to write:

The fact is that assignment-as-an-operator is a very useful construct. We didn't eliminate razor blades because some people cut themselves. Instead, King Gillette invented the safety razor.

John R. Strohm's user avatar

  • 2 (1) := for assignment and = for equality might fix this problem, but at the cost of alienating every programmer who didn't grow up using a small set of non-mainstream languages. (2) Types other than bools being allows in conditions isn't always due to mixing up bools and integers, it's sufficient to give a true/false interpretation to other types. Newer language that aren't afraid to deviate from C have done so for many types other than integers (e.g. Python considers empty collections false). –  user7043 Commented Feb 13, 2014 at 13:38
  • 1 And regarding razor blades: Those serve a use case that necessitates sharpness. On the other hand, I'm not convinced programming well requires assigning to variables in the middle of an expression evaluation. If there was a simple, low-tech, safe and cost efficient way to make body hair disappear without sharp edges, I'm sure razor blades would have been displaced or at least made much more rare. –  user7043 Commented Feb 13, 2014 at 13:40
  • 1 @delnan: A wise man once said "Make it as simple as possible, but no simpler." If your objective is to eliminate the vast majority of a=b vs. a==b errors, restricting the domain of conditional tests to booleans and eliminating the default type conversion rules for <other>->boolean gets you just about all the way there. At that point, if(a=b){} is only syntactically legal if a and b are both boolean and a is a legal lvalue. –  John R. Strohm Commented Feb 13, 2014 at 15:07
  • Making assignment a statement is at least as simple as -- arguably even simpler than -- the changes you propose, and achieves at least as much -- arguably even more (doesn't even permit if (a = b) for lvalue a, boolean a, b). In a language without static typing, it also gives much better error messages (at parse time vs. run time). In addition, preventing "a=b vs. a==b errors" may not be the only relevant objective. For example, I'd also like to permit code like if items: to mean if len(items) != 0 , and that I'd have to give up to restrict conditions to booleans. –  user7043 Commented Feb 13, 2014 at 15:14
  • 1 @delnan Pascal is a non-mainstream language? Millions of people learned programming using Pascal (and/or Modula, which derives from Pascal). And Delphi is still commonly used in many countries (maybe not so much in yours). –  jwenting Commented Feb 14, 2014 at 9:39

To actually answer the question, yes there are numerous uses of this although they are slightly niche.

For example in Java:

The alternative without using the embedded assignment requires the ob defined outside the scope of the loop and two separate code locations that call x.next().

It's already been mentioned that you can assign multiple variables in one step.

This sort of thing is the most common use, but creative programmers will always come up with more.

Tim B's user avatar

  • Would that while loop condition deallocate and create a new ob object with every loop? –  user3932000 Commented May 3, 2017 at 22:33
  • @user3932000 In that case probably not, usually x.next() is iterating over something. It is certainly possible that it could though. –  Tim B Commented May 4, 2017 at 8:18
  • I can't get the above to compile unless I declare the variable beforehand and remove the declaration from inside. It says Object cannot be resolved to a variable. –  William Jarvis Commented Apr 15, 2021 at 16:42

Since you get to make up all the rules, why now allow assignment to turn a value, and simply not allow assignments inside conditional steps? This gives you the syntactic sugar to make initializations easy, while still preventing a common coding mistake.

In other words, make this legal:

But make this illegal:

Bryan Oakley's user avatar

  • 2 That seems like a rather ad-hoc rule. Making assignment a statement and extending it to allow a = b = c seems more orthogonal, and easier to implement too. These two approach disagree about assignment in expressions ( a + (b = c) ), but you haven't taken sides on those so I assume they don't matter. –  user7043 Commented Feb 13, 2014 at 13:01
  • "easy to implement" shouldn't be much of a consideration. You are defining a user interface -- put the needs of the users first. You simply need to ask yourself whether this behavior helps or hinders the user. –  Bryan Oakley Commented Feb 13, 2014 at 13:05
  • if you disallow implicit conversion to bool then you don't have to worry about assignment in conditions –  ratchet freak Commented Feb 13, 2014 at 13:08
  • Easier to implement was only one of my arguments. What about the rest? From the UI angle, I might add that IMHO incoherent design and ad-hoc exceptions generally hinders the user in grokking and internalising the rules. –  user7043 Commented Feb 13, 2014 at 13:10
  • @ratchetfreak you could still have an issue with assigning actual bools –  jk. Commented Feb 13, 2014 at 13:25

By the sounds of it, you are on the path of creating a fairly strict language.

With that in mind, forcing people to write:

instead of:

might seem an improvement to prevent people from doing:

when they meant to do:

but in the end, this kind of errors are easy to detect and warn about whether or not they are legal code.

However, there are situations where doing:

does not mean that

will be true.

If c is actually a function c() then it could return different results each time it is called. (it might also be computationally expensive too...)

Likewise if c is a pointer to memory mapped hardware, then

are both likely to be different, and also may also have electronic effects on the hardware on each read.

There are plenty of other permutations with hardware where you need to be precise about what memory addresses are read from, written to and under specific timing constraints, where doing multiple assignments on the same line is quick, simple and obvious, without the timing risks that temporary variables introduce

Michael Shaw's user avatar

  • 4 The equivalent to a = b = c isn't a = c; b = c , it's b = c; a = b . This avoids duplication of side effects and also keeps the modification of a and b in the same order. Also, all these hardware-related arguments are kind of stupid: Most languages are not system languages and are neither designed to solve these problems nor are they being used in situations where these problems occur. This goes doubly for a language that attempts to displace JavaScript and/or PHP. –  user7043 Commented Feb 13, 2014 at 13:04
  • delnan, the issue wasn't are these contrived examples, they are. The point still stands that they show the kinds of places where writing a=b=c is common, and in the hardware case, considered good practice, as the OP asked for. I'm sure they will be able to consider their relevance to their expected environment –  Michael Shaw Commented Feb 13, 2014 at 13:51
  • Looking back, my problem with this answer is not primarily that it focuses on system programming use cases (though that would be bad enough, the way it's written), but that it rests on assuming an incorrect rewriting. The examples aren't examples of places where a=b=c is common/useful, they are examples of places where order and number of side effects must be taken care of. That is entirely independent. Rewrite the chained assignment correctly and both variants are equally correct. –  user7043 Commented Feb 13, 2014 at 13:58
  • @delnan: The rvalue is converted to the type of b in one temp, and that is converted to the type of a in another temp. The relative timing of when those values are actually stored is unspecified. From a language-design perspective, I would think it reasonable to require that all lvalues in a multiple-assignment statement have matching type, and possibly to require as well that none of them be volatile. –  supercat Commented Feb 13, 2014 at 19:17

The greatest benefit to my mind of having assignment be an expression is that it allows your grammar to be simpler if one of your goals is that "everything is an expression"--a goal of LISP in particular.

Python does not have this; it has expressions and statements, assignment being a statement. But because Python defines a lambda form as being a single parameterized expression , that means you can't assign variables inside a lambda. This is inconvenient at times, but not a critical issue, and it's about the only downside in my experience to having assignment be a statement in Python.

One way to allow assignment, or rather the effect of assignment, to be an expression without introducing the potential for if(x=1) accidents that C has is to use a LISP-like let construct, such as (let ((x 2) (y 3)) (+ x y)) which might in your language evaluate as 5 . Using let this way need not technically be assignment at all in your language, if you define let as creating a lexical scope. Defined that way, a let construct could be compiled the same way as constructing and calling a nested closure function with arguments.

On the other hand, if you are simply concerned with the if(x=1) case, but want assignment to be an expression as in C, maybe just choosing different tokens will suffice. Assignment: x := 1 or x <- 1 . Comparison: x == 1 . Syntax error: x = 1 .

wberry's user avatar

  • 1 let differs from assignment in more ways than technically introducing a new variable in a new scope. For starters, it has no effect on code outside the let 's body, and therefore requires nesting all code (what should use the variable) further, a significant downside in assignment-heavy code. If one was to go down that route, set! would be the better Lisp analogue - completely unlike comparison, yet not requiring nesting or a new scope. –  user7043 Commented Feb 13, 2014 at 21:36
  • @delnan: I'd like to see a combination declare-and-assign syntax which would prohibit reassignment but would allow redeclaration, subject to the rules that (1) redeclaration would only be legal for declare-and-assign identifiers, and (2) redeclaration would "undeclare" a variable in all enclosing scopes. Thus, the value of any valid identifier would be whatever was assigned in the previous declaration of that name. That would seem a little nicer than having to add scoping blocks for variables that are only used for a few lines, or having to formulate new names for each temp variable. –  supercat Commented Feb 14, 2014 at 3:08

Indeed. This is nothing new, all the safe subsets of the C language have already made this conclusion.

MISRA-C, CERT-C and so on all ban assignment inside conditions, simply because it is dangerous.

There exists no case where code relying on assignment inside conditions cannot be rewritten.

Furthermore, such standards also warns against writing code that relies on the order of evaluation. Multiple assignments on one single row x=y=z; is such a case. If a row with multiple assignments contains side effects (calling functions, accessing volatile variables etc), you cannot know which side effect that will occur first.

There are no sequence points between the evaluation of the operands. So we cannot know whether the subexpression y gets evaluated before or after z : it is unspecified behavior in C. Thus such code is potentially unreliable, non-portable and non-conformant to the mentioned safe subsets of C.

The solution would have been to replace the code with y=z; x=y; . This adds a sequence point and guarantees the order of evaluation.

So based on all the problems this caused in C, any modern language would do well to both ban assignment inside conditions, as well as multiple assignments on one single row.

Not the answer you're looking for? Browse other questions tagged language-agnostic syntax operators or ask your own question .

  • The Overflow Blog
  • This developer tool is 40 years old: can it be improved?
  • Unpacking the 2024 Developer Survey results
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Introducing an accessibility dashboard and some upcoming changes to display...

Function expressions

In JavaScript, a function is not a “magical language structure”, but a special kind of value.

The syntax that we used before is called a Function Declaration :

There is another syntax for creating a function that is called a Function Expression .

It allows us to create a new function in the middle of any expression.

For example:

Here we can see a variable sayHi getting a value, the new function, created as function() { alert("Hello"); } .

As the function creation happens in the context of the assignment expression (to the right side of = ), this is a Function Expression .

Please note, there’s no name after the function keyword. Omitting a name is allowed for Function Expressions.

Here we immediately assign it to the variable, so the meaning of these code samples is the same: "create a function and put it into the variable sayHi ".

In more advanced situations, that we’ll come across later, a function may be created and immediately called or scheduled for a later execution, not stored anywhere, thus remaining anonymous.

Function is a value

Let’s reiterate: no matter how the function is created, a function is a value. Both examples above store a function in the sayHi variable.

We can even print out that value using alert :

Please note that the last line does not run the function, because there are no parentheses after sayHi . There are programming languages where any mention of a function name causes its execution, but JavaScript is not like that.

In JavaScript, a function is a value, so we can deal with it as a value. The code above shows its string representation, which is the source code.

Surely, a function is a special value, in the sense that we can call it like sayHi() .

But it’s still a value. So we can work with it like with other kinds of values.

We can copy a function to another variable:

Here’s what happens above in detail:

  • The Function Declaration (1) creates the function and puts it into the variable named sayHi .
  • Line (2) copies it into the variable func . Please note again: there are no parentheses after sayHi . If there were, then func = sayHi() would write the result of the call sayHi() into func , not the function sayHi itself.
  • Now the function can be called as both sayHi() and func() .

We could also have used a Function Expression to declare sayHi , in the first line:

Everything would work the same.

You might wonder, why do Function Expressions have a semicolon ; at the end, but Function Declarations do not:

The answer is simple: a Function Expression is created here as function(…) {…} inside the assignment statement: let sayHi = …; . The semicolon ; is recommended at the end of the statement, it’s not a part of the function syntax.

The semicolon would be there for a simpler assignment, such as let sayHi = 5; , and it’s also there for a function assignment.

Callback functions

Let’s look at more examples of passing functions as values and using function expressions.

We’ll write a function ask(question, yes, no) with three parameters:

The function should ask the question and, depending on the user’s answer, call yes() or no() :

In practice, such functions are quite useful. The major difference between a real-life ask and the example above is that real-life functions use more complex ways to interact with the user than a simple confirm . In the browser, such functions usually draw a nice-looking question window. But that’s another story.

The arguments showOk and showCancel of ask are called callback functions or just callbacks .

The idea is that we pass a function and expect it to be “called back” later if necessary. In our case, showOk becomes the callback for “yes” answer, and showCancel for “no” answer.

We can use Function Expressions to write an equivalent, shorter function:

Here, functions are declared right inside the ask(...) call. They have no name, and so are called anonymous . Such functions are not accessible outside of ask (because they are not assigned to variables), but that’s just what we want here.

Such code appears in our scripts very naturally, it’s in the spirit of JavaScript.

Regular values like strings or numbers represent the data .

A function can be perceived as an action .

We can pass it between variables and run when we want.

Function Expression vs Function Declaration

Let’s formulate the key differences between Function Declarations and Expressions.

First, the syntax: how to differentiate between them in the code.

Function Declaration: a function, declared as a separate statement, in the main code flow:

Function Expression: a function, created inside an expression or inside another syntax construct. Here, the function is created on the right side of the “assignment expression” = :

The more subtle difference is when a function is created by the JavaScript engine.

A Function Expression is created when the execution reaches it and is usable only from that moment.

Once the execution flow passes to the right side of the assignment let sum = function… – here we go, the function is created and can be used (assigned, called, etc. ) from now on.

Function Declarations are different.

A Function Declaration can be called earlier than it is defined.

For example, a global Function Declaration is visible in the whole script, no matter where it is.

That’s due to internal algorithms. When JavaScript prepares to run the script, it first looks for global Function Declarations in it and creates the functions. We can think of it as an “initialization stage”.

And after all Function Declarations are processed, the code is executed. So it has access to these functions.

For example, this works:

The Function Declaration sayHi is created when JavaScript is preparing to start the script and is visible everywhere in it.

…If it were a Function Expression, then it wouldn’t work:

Function Expressions are created when the execution reaches them. That would happen only in the line (*) . Too late.

Another special feature of Function Declarations is their block scope.

In strict mode, when a Function Declaration is within a code block, it’s visible everywhere inside that block. But not outside of it.

For instance, let’s imagine that we need to declare a function welcome() depending on the age variable that we get during runtime. And then we plan to use it some time later.

If we use Function Declaration, it won’t work as intended:

That’s because a Function Declaration is only visible inside the code block in which it resides.

Here’s another example:

What can we do to make welcome visible outside of if ?

The correct approach would be to use a Function Expression and assign welcome to the variable that is declared outside of if and has the proper visibility.

This code works as intended:

Or we could simplify it even further using a question mark operator ? :

As a rule of thumb, when we need to declare a function, the first thing to consider is Function Declaration syntax. It gives more freedom in how to organize our code, because we can call such functions before they are declared.

That’s also better for readability, as it’s easier to look up function f(…) {…} in the code than let f = function(…) {…}; . Function Declarations are more “eye-catching”.

…But if a Function Declaration does not suit us for some reason, or we need a conditional declaration (we’ve just seen an example), then Function Expression should be used.

  • Functions are values. They can be assigned, copied or declared in any place of the code.
  • If the function is declared as a separate statement in the main code flow, that’s called a “Function Declaration”.
  • If the function is created as a part of an expression, it’s called a “Function Expression”.
  • Function Declarations are processed before the code block is executed. They are visible everywhere in the block.
  • Function Expressions are created when the execution flow reaches them.

In most cases when we need to declare a function, a Function Declaration is preferable, because it is visible prior to the declaration itself. That gives us more flexibility in code organization, and is usually more readable.

So we should use a Function Expression only when a Function Declaration is not fit for the task. We’ve seen a couple of examples of that in this chapter, and will see more in the future.

Lesson navigation

  • © 2007—2024  Ilya Kantor
  • about the project
  • terms of usage
  • privacy policy
  • DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter

JavaScript return Statement

The return statement in JavaScript is used to end the execution of a function and specifies the value to be returned by that function. The return statement stops the execution of a function and returns a value. It’s particularly useful for passing data back to the code that called the function, allowing for dynamic program flow and data processing.

It can be used to return a specific value, variable, or expression to the caller. If no value is provided, the function returns undefined by default.

  • value: The value returned to the function caller. It is an optional parameter. If the value is not specified, the function returns undefined

JavaScript return Statement Examples

Example 1: This code defines a function `Product(a, b)` that takes two parameters `a` and `b`. It returns the product of `a` and `b` by multiplying them. Then, it calls the `Product()` function with arguments `6` and `10` and logs the result, which is `60`.

Example 2: Here, we will return multiple values by using the object and we are using ES6 object destructuring to unpack the value of the object.

Here, the code defines a function `Language()` that returns an object containing three properties: `first`, `second`, and `Third`, each storing a string value. Then, it uses object destructuring to assign these properties to variables `first`, `second`, and `Third`. Finally, it logs the values of these variables.

Please Login to comment...

Similar reads.

  • Web Technologies
  • JavaScript Statements-and-declarations

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

JS Tutorial

Js versions, js functions, js html dom, js browser bom, js web apis, js vs jquery, js graphics, js examples, js references, javascript functions.

A JavaScript function is a block of code designed to perform a particular task.

A JavaScript function is executed when "something" invokes it (calls it).

JavaScript Function Syntax

A JavaScript function is defined with the function keyword, followed by a name , followed by parentheses () .

Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).

The parentheses may include parameter names separated by commas: ( parameter1, parameter2, ... )

The code to be executed, by the function, is placed inside curly brackets: {}

Function parameters are listed inside the parentheses () in the function definition.

Function arguments are the values received by the function when it is invoked.

Inside the function, the arguments (the parameters) behave as local variables.

Function Invocation

The code inside the function will execute when "something" invokes (calls) the function:

  • When an event occurs (when a user clicks a button)
  • When it is invoked (called) from JavaScript code
  • Automatically (self invoked)

You will learn a lot more about function invocation later in this tutorial.

Advertisement

Function Return

When JavaScript reaches a return statement, the function will stop executing.

If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement.

Functions often compute a return value . The return value is "returned" back to the "caller":

Calculate the product of two numbers, and return the result:

Why Functions?

With functions you can reuse code

You can write code that can be used many times.

You can use the same code with different arguments, to produce different results.

The () Operator

The () operator invokes (calls) the function:

Convert Fahrenheit to Celsius:

Accessing a function with incorrect parameters can return an incorrect answer:

Accessing a function without () returns the function and not the function result:

As you see from the examples above, toCelsius refers to the function object, and toCelsius() refers to the function result.

Functions Used as Variable Values

Functions can be used the same way as you use variables, in all types of formulas, assignments, and calculations.

Instead of using a variable to store the return value of a function:

You can use the function directly, as a variable value:

You will learn a lot more about functions later in this tutorial.

Local Variables

Variables declared within a JavaScript function, become LOCAL to the function.

Local variables can only be accessed from within the function.

Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.

Local variables are created when a function starts, and deleted when the function is completed.

Test Yourself With Exercises

Execute the function named myFunction .

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Arrow function should not return assignment?

My code is working correctly in the app however, my eslint isn't liking it and is saying I should not return assignment. What is wrong with this?

AnnaSm's user avatar

  • 4 add { } around it –  epascarello Commented Jan 24, 2018 at 1:00
  • it's a warning, try <div ref={(el) => (this.myCustomEl = el)} /> –  Jaromanda X Commented Jan 24, 2018 at 1:01
  • Same warning. while it's a warning, I can't pass tests with the warning –  AnnaSm Commented Jan 24, 2018 at 1:09
  • 3 <div ref={(el) => { this.myCustomEl = e}l} /> –  epascarello Commented Jan 24, 2018 at 1:11
  • 1 @epascarello typo with the e}l ? –  AnnaSm Commented Jan 24, 2018 at 1:13

4 Answers 4

The Explanation:

Your current code

is equivalent to:

You are returning the result of this.myCustomEl = el. In your code, this is not really a problem -- however, one of the most frustrating bugs in programming occurs when you accidentally use an assignment (=) instead of a comparator (== or ===), for instance:

In the above case, the compiler warning makes sense because k=true evaluates to true (as opposed to k===true , which is probably what you meant to type) and causes unintended behavior. Thus, eshint notices when you return an assignment, assumes that you meant to return a comparison, and lets you know that you should be careful.

In your case, you can solve this by simply not returning the result, which is done by adding enclosing brackets {} and no return statement:

You can also adjust the eshint warning like so: https://eslint.org/docs/rules/no-return-assign

izogfif's user avatar

You're implicitly returning an assignment. this.myCustomEl = el is an assignment. You could fix this linting error by changing your arrow function to (el) => { this.myCustomEl =el } which is no longer implicitly returning because you wrapped it in {} instead of () .

Side note : Declaring an arrow function inline inside a render method will break a PureComponent because every time your component renders it has to declare a new anonymous function, so the shallow props comparison that a PureComponent does is broken by this and will always re-render.

Try making that a method of your component.

If the above syntax doesn't work for you, you can use the following:

Kyle Richardson's user avatar

  • FYI, this errors w "Cannot read property 'appendChild' of undefined" –  AnnaSm Commented Jan 24, 2018 at 17:00
  • You can see it working in this code sandbox example . –  Kyle Richardson Commented Jan 24, 2018 at 19:53

Just wanted to note something I came across. I have Prettier installed and it kept taking away my parens, resulting in eslint error: To confirm this I added a prettier-ignore:

Christopher Adams's user avatar

Eslint will give us error message if we not applied flowe bracket

KARTHIKEYAN.A's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged javascript reactjs eslint or ask your own question .

  • The Overflow Blog
  • This developer tool is 40 years old: can it be improved?
  • Unpacking the 2024 Developer Survey results
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Introducing an accessibility dashboard and some upcoming changes to display...
  • Tag hover experiment wrap-up and next steps

Hot Network Questions

  • What purpose did the lower-right "Enter" key serve on the original Mac 128k keyboard?
  • How does "regina" derive from "rex"?
  • What's "unregulated baggage"?
  • An English equivalent of the Japanese idiom "be tied with a red string (of destiny)"
  • What role can scrum master have/take when product owners have different opinions?
  • Solar System Replacement?
  • Relay contact welding detection with opto-coupler (both on line and neutral)
  • How do the Fremen harvest spice?
  • What is so special about JUICE's flyby with Earth and Moon?
  • What is this bracket on the side of my shower called? I believe it may have held a soap dish
  • Why don't aircraft use D.C generators?
  • Can I say "he lived in silk" to mean he had a luxury life in which he was pampered with luxurious things?
  • If my character has the same name as a character from another story, will the publisher tell me to change it?
  • What are those small notes below other ones?
  • Did Einstein say the one-way speed-of-light is "not a fact of nature"?
  • Who checks and balances SCOTUS?
  • Criterion for a rational variety being the projective space
  • GND plane on both sides?
  • A spaceship travelling at speed of light
  • Why is “water takes the steepest path downhill” a common approximation?
  • When/why did software only engines overtake custom hardware?
  • Are these friction shifters?
  • What does "No camping 10-21" mean?
  • AttributeError: DescribeData: Method spatialReference does not exist when iterating listLayers()

javascript function return assignment

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

Arrow function expressions

An arrow function expression is a compact alternative to a traditional function expression , with some semantic differences and deliberate limitations in usage:

  • Arrow functions don't have their own bindings to this , arguments , or super , and should not be used as methods .
  • Arrow functions cannot be used as constructors . Calling them with new throws a TypeError . They also don't have access to the new.target keyword.
  • Arrow functions cannot use yield within their body and cannot be created as generator functions.

Rest parameters , default parameters , and destructuring within params are supported, and always require parentheses:

Arrow functions can be async by prefixing the expression with the async keyword.

Description

Let's decompose a traditional anonymous function down to the simplest arrow function step-by-step. Each step along the way is a valid arrow function.

Note: Traditional function expressions and arrow functions have more differences than their syntax. We will introduce their behavior differences in more detail in the next few subsections.

In the example above, both the parentheses around the parameter and the braces around the function body may be omitted. However, they can only be omitted in certain cases.

The parentheses can only be omitted if the function has a single simple parameter. If it has multiple parameters, no parameters, or default, destructured, or rest parameters, the parentheses around the parameter list are required.

The braces can only be omitted if the function directly returns an expression. If the body has statements, the braces are required — and so is the return keyword. Arrow functions cannot guess what or when you want to return.

Arrow functions are not inherently associated with a name. If the arrow function needs to call itself, use a named function expression instead. You can also assign the arrow function to a variable, allowing you to refer to it through that variable.

Function body

Arrow functions can have either an expression body or the usual block body .

In an expression body, only a single expression is specified, which becomes the implicit return value. In a block body, you must use an explicit return statement.

Returning object literals using the expression body syntax (params) => { object: literal } does not work as expected.

This is because JavaScript only sees the arrow function as having an expression body if the token following the arrow is not a left brace, so the code inside braces ({}) is parsed as a sequence of statements, where foo is a label , not a key in an object literal.

To fix this, wrap the object literal in parentheses:

Cannot be used as methods

Arrow function expressions should only be used for non-method functions because they do not have their own this . Let's see what happens when we try to use them as methods:

Another example involving Object.defineProperty() :

Because a class 's body has a this context, arrow functions as class fields close over the class's this context, and the this inside the arrow function's body will correctly point to the instance (or the class itself, for static fields ). However, because it is a closure , not the function's own binding, the value of this will not change based on the execution context.

Arrow function properties are often said to be "auto-bound methods", because the equivalent with normal methods is:

Note: Class fields are defined on the instance , not on the prototype , so every instance creation would create a new function reference and allocate a new closure, potentially leading to more memory usage than a normal unbound method.

For similar reasons, the call() , apply() , and bind() methods are not useful when called on arrow functions, because arrow functions establish this based on the scope the arrow function is defined within, and the this value does not change based on how the function is invoked.

No binding of arguments

Arrow functions do not have their own arguments object. Thus, in this example, arguments is a reference to the arguments of the enclosing scope:

Note: You cannot declare a variable called arguments in strict mode , so the code above would be a syntax error. This makes the scoping effect of arguments much easier to comprehend.

In most cases, using rest parameters is a good alternative to using an arguments object.

Cannot be used as constructors

Arrow functions cannot be used as constructors and will throw an error when called with new . They also do not have a prototype property.

Cannot be used as generators

The yield keyword cannot be used in an arrow function's body (except when used within generator functions further nested within the arrow function). As a consequence, arrow functions cannot be used as generators.

Line break before arrow

An arrow function cannot contain a line break between its parameters and its arrow.

For the purpose of formatting, you may put the line break after the arrow or use parentheses/braces around the function body, as shown below. You can also put line breaks between parameters.

Precedence of arrow

Although the arrow in an arrow function is not an operator, arrow functions have special parsing rules that interact differently with operator precedence compared to regular functions.

Because => has a lower precedence than most operators, parentheses are necessary to avoid callback || () being parsed as the arguments list of the arrow function.

Using arrow functions

Using call, bind, and apply.

The call() , apply() , and bind() methods work as expected with traditional functions, because we establish the scope for each of the methods:

With arrow functions, since our add function is essentially created on the globalThis (global) scope, it will assume this is the globalThis .

Perhaps the greatest benefit of using arrow functions is with methods like setTimeout() and EventTarget.prototype.addEventListener() that usually require some kind of closure, call() , apply() , or bind() to ensure that the function is executed in the proper scope.

With traditional function expressions, code like this does not work as expected:

With arrow functions, the this scope is more easily preserved:

Specifications

Specification

Browser compatibility

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

  • Functions guide
  • function expression
  • ES6 In Depth: Arrow functions on hacks.mozilla.org (2015)

IMAGES

  1. JavaScript Function and Function Expressions (with Examples)

    javascript function return assignment

  2. Return Js

    javascript function return assignment

  3. Assignment with a Returned Value, freeCodeCamp Basic Javascript

    javascript function return assignment

  4. How to Return Multiple Values from a Function in JavaScript

    javascript function return assignment

  5. JavaScript Functions

    javascript function return assignment

  6. JavaScript Return Statement

    javascript function return assignment

VIDEO

  1. Use Destructuring Assignment to Pass an Object as a Function's Parameters (ES6) freeCodeCamp

  2. Assignment with a Returned Value (Basic JavaScript) freeCodeCamp tutorial

  3. Passing Values to Functions with Arguments (Basic JavaScript) freeCodeCamp tutorial

  4. Parameters and Arguments in JavaScript

  5. Java Script Tutorial Episode-17

  6. 8 ways to create javascript object

COMMENTS

  1. assign function return value to some variable using javascript

    The only way to retrieve the correct value in your context is to run $.ajax() function synchronously (what actually contradicts to main AJAX idea). There is the special configuration attribute async you should set to false.In that case the main scope which actually contains $.ajax() function call is paused until the synchronous function is done, so, the return is called only after $.ajax().

  2. javascript

    Second thing is assigning y to x, and so on. Assigning is not return (it's not a function, and in JS it doesn't have C++ syntax to overload operator's behavior). return is sth more complex then assignment. return construct is not only returning a value, but is closing current context causing it to be destroyed. Also it's closing any parent ...

  3. Function return values

    The substring to find ('cold') The string to replace it with ('warm') When the function completes (finishes running), it returns a value, which is a new string with the replacement made. In the code above, the result of this return value is saved in the variable newString. If you look at the replace() function MDN reference page, you'll see a ...

  4. return

    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.

  5. JavaScript return Statement

    The return statement stops the execution of a function and returns a value. Read our JavaScript Tutorial to learn all you need to know about functions. Start with the introduction chapter about JavaScript Functions and JavaScript Scope. For more detailed information, see our Function Section on Function Definitions , Parameters , Invocation and ...

  6. Functions

    Functions are one of the fundamental building blocks in JavaScript. A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output. To use a function, you must define it ...

  7. Assignment with a Returned Value

    This means we can take the return value of a function and assign it to a variable. Assume we have pre-defined a function sum that adds two numbers together, then: 📋 copy. jsx. 1. ourSum = sum(5, 12); will call the sum function, which returns a value of 17 and assigns it to the ourSum variable. Discord. 1/9.

  8. JavaScript Function Parameters

    The parameters, in a function call, are the function's arguments. JavaScript arguments are passed by value: The function only gets to know the values, not the argument's locations. If a function changes an argument's value, it does not change the parameter's original value. Changes to arguments are not visible (reflected) outside the function.

  9. Returning Multiple Values from a Function

    Returning multiple values from an function using an object. If you want to assign a name to each returned value to make it more readable and easier to maintain, you can use an object: function getNames() {. // get names from the database or API let firstName = 'John' , lastName = 'Doe' ; // return values return {.

  10. Assignment (=)

    The assignment (=) operator is used to assign a value to a variable or property. The assignment expression itself has a value, which is the assigned value. ... return not in function; SyntaxError: setter functions must have one argument ... Note that the implication of the above is that, contrary to popular misinformation, JavaScript does not ...

  11. What is the benefit of having the assignment operator return a value?

    while ((Object ob = x.next()) != null) { // This will loop through calling next() until it returns null // The value of the returned object is available as ob within the loop } The alternative without using the embedded assignment requires the ob defined outside the scope of the loop and two separate code locations that call x.next().

  12. Function expressions

    A Function Expression is created when the execution reaches it and is usable only from that moment. Once the execution flow passes to the right side of the assignment let sum = function… - here we go, the function is created and can be used (assigned, called, etc. ) from now on. Function Declarations are different.

  13. JavaScript return Statement

    The return statement stops the execution of a function and returns a value. It's particularly useful for passing data back to the code that called the function, allowing for dynamic program flow and data processing. It can be used to return a specific value, variable, or expression to the caller. If no value is provided, the function returns ...

  14. javascript

    An assignment assigns a value to variable. A return statement returns a value from a function. They are two different operations with different purposes. The data type of the value is irrelevant. This is also not specific to JavaScript, these operations exist in most programming languages.

  15. Functions

    Generally speaking, a function is a "subprogram" that can be called by code external (or internal, in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function as parameters, and the function will return a value.

  16. JavaScript Functions

    Function Return. When JavaScript reaches a return statement, the function will stop executing. If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement. Functions often compute a return value. The return value is "returned" back to the "caller":

  17. Object.assign()

    Later sources' properties overwrite earlier ones. The Object.assign() method only copies enumerable and own properties from a source object to a target object. It uses [[Get]] on the source and [[Set]] on the target, so it will invoke getters and setters. Therefore it assigns properties, versus copying or defining new properties.

  18. JavaScript assignment in return statement

    2. No, there is no functional reason to do this. Since the result of param = 10, is indeed 10, there's no functional difference between; return param = 10; return 10; While benchmarking the code, returning the assingment slows down the code; 100% vs 99.46%. The only reason I could imagine a developer to choose this option, is to let further ...

  19. Arrow function should not return assignment?

    // This function will always return **true**, surprisingly function isEqual(a, b) { // The warning would be thrown here, because you probably meant to type "a===b". ... Thus, eshint notices when you return an assignment, assumes that you meant to return a comparison, and lets you know that you should be careful. In your case, you can solve this ...

  20. Arrow function expressions

    Remove the word "function" and place arrow between the argument and opening body brace (a) => { return a + 100; }; // 2. Remove the body braces and word "return" — the return is implied. (a) => a + 100; // 3. Remove the parameter parentheses a => a + 100; In the example above, both the parentheses around the parameter and the braces around ...