AI Creations
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.
JS Reference
Html events, html objects, other references, javascript return.
Return the value of PI:
Return "Hello John":
More examples below.
Description
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 Closures .
Parameter | Description |
Optional. The value to be returned. If omitted, it returns |
Advertisement
More Examples
Calculate the product of two numbers and return the result:
Related Pages
JavaScript Tutorial: JavaScript Functions
JavaScript Tutorial: JavaScript Scope
JavaScript Tutorial: JavaScript Function Definitions
JavaScript Tutorial: JavaScript Function Parameters
JavaScript Tutorial: JavaScript Function Invocation
JavaScript Tutorial: JavaScript Function Closures
JavaScript Reference: JavaScript function Statement
Browser Support
return is an ECMAScript1 (ES1) feature.
ES1 (JavaScript 1997) is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
COLOR PICKER
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 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
- 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 .
- 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.
- +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.
- 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.
- 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:
- 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
- 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 .
- 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
- Scaling systems to manage all the metadata ABOUT the data
- Navigating cities of code with Norris Numbers
- Featured on Meta
- We've made changes to our Terms of Service & Privacy Policy - July 2024
- Bringing clarity to status tag usage on meta sites
Hot Network Questions
- How to model drug adsorption on nanomaterial?
- A post-apocalyptic short story where very sick people from our future save people in our timeline that would be killed in plane crashes
- Is groff ignoring `.nh` command?
- Blocking between two MERGE queries inserting into the same table
- To what extent do value sets determine polynomials mod p?
- How can I vertically align LEDs in a LaTeX circuit diagram using Circuitikz?
- Double and single delta-function potential well energy similarity
- Rock paper scissor game in Javascript
- When would it be legal to ask back (parts of) the salary?
- Sharing course material from a previous lecturer with a new lecturer
- Word to classify what powers a god is associated with?
- Why does Air Force Two lack a tail number?
- Does the First Amendment protect deliberately publicizing the incorrect date for an election?
- Erase the loops
- Can you bring a cohort back to life?
- How can I obscure branding on the side of a pure white ceramic sink?
- Why do individuals with revoked master’s/PhD degrees due to plagiarism or misconduct not return to retake them?
- How to Vertically Join Images?
- Is an invalid date considered the same as a NULL value?
- Returning to France with a Récépissé de Demande de Carte de Séjour stopping at Zurich first
- How do Christians determine which messianic prophecies are to be fulfilled by the 'Second Coming'?
- John 11 and The Sanhedrin Council
- Is there any point "clean-installing" on a brand-new MacBook?
- Will the american customs be suspicious of my luggage if i bought a lot of the same item?
- Skip to main content
- Skip to search
- Skip to select language
- Sign up for free
- PortuguĆŖs (doĀ Brasil)
Destructuring assignment
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
Description
The object and array literal expressions provide an easy way to create ad hoc packages of data.
The destructuring assignment uses similar syntax but uses it on the left-hand side of the assignment instead. It defines which values to unpack from the sourced variable.
Similarly, you can destructure objects on the left-hand side of the assignment.
This capability is similar to features present in languages such as Perl and Python.
For features specific to array or object destructuring, refer to the individual examples below.
Binding and assignment
For both object and array destructuring, there are two kinds of destructuring patterns: binding pattern and assignment pattern , with slightly different syntaxes.
In binding patterns, the pattern starts with a declaration keyword ( var , let , or const ). Then, each individual property must either be bound to a variable or further destructured.
All variables share the same declaration, so if you want some variables to be re-assignable but others to be read-only, you may have to destructure twice ā once with let , once with const .
In many other syntaxes where the language binds a variable for you, you can use a binding destructuring pattern. These include:
- The looping variable of for...in for...of , and for await...of loops;
- Function parameters;
- The catch binding variable.
In assignment patterns, the pattern does not start with a keyword. Each destructured property is assigned to a target of assignment ā which may either be declared beforehand with var or let , or is a property of another object ā in general, anything that can appear on the left-hand side of an assignment expression.
Note: The parentheses ( ... ) around the assignment statement are required when using object literal destructuring assignment without a declaration.
{ a, b } = { a: 1, b: 2 } is not valid stand-alone syntax, as the { a, b } on the left-hand side is considered a block and not an object literal according to the rules of expression statements . However, ({ a, b } = { a: 1, b: 2 }) is valid, as is const { a, b } = { a: 1, b: 2 } .
If your coding style does not include trailing semicolons, the ( ... ) expression needs to be preceded by a semicolon, or it may be used to execute a function on the previous line.
Note that the equivalent binding pattern of the code above is not valid syntax:
You can only use assignment patterns as the left-hand side of the assignment operator. You cannot use them with compound assignment operators such as += or *= .
Default value
Each destructured property can have a default value . The default value is used when the property is not present, or has value undefined . It is not used if the property has value null .
The default value can be any expression. It will only be evaluated when necessary.
Rest property
You can end a destructuring pattern with a rest property ...rest . This pattern will store all remaining properties of the object or array into a new object or array.
The rest property must be the last in the pattern, and must not have a trailing comma.
Array destructuring
Basic variable assignment, destructuring with more elements than the source.
In an array destructuring from an array of length N specified on the right-hand side of the assignment, if the number of variables specified on the left-hand side of the assignment is greater than N , only the first N variables are assigned values. The values of the remaining variables will be undefined.
Swapping variables
Two variables values can be swapped in one destructuring expression.
Without destructuring assignment, swapping two values requires a temporary variable (or, in some low-level languages, the XOR-swap trick ).
Parsing an array returned from a function
It's always been possible to return an array from a function. Destructuring can make working with an array return value more concise.
In this example, f() returns the values [1, 2] as its output, which can be parsed in a single line with destructuring.
Ignoring some returned values
You can ignore return values that you're not interested in:
You can also ignore all returned values:
Using a binding pattern as the rest property
The rest property of array destructuring assignment can be another array or object binding pattern. The inner destructuring destructures from the array created after collecting the rest elements, so you cannot access any properties present on the original iterable in this way.
These binding patterns can even be nested, as long as each rest property is the last in the list.
On the other hand, object destructuring can only have an identifier as the rest property.
Unpacking values from a regular expression match
When the regular expression exec() method finds a match, it returns an array containing first the entire matched portion of the string and then the portions of the string that matched each parenthesized group in the regular expression. Destructuring assignment allows you to unpack the parts out of this array easily, ignoring the full match if it is not needed.
Using array destructuring on any iterable
Array destructuring calls the iterable protocol of the right-hand side. Therefore, any iterable, not necessarily arrays, can be destructured.
Non-iterables cannot be destructured as arrays.
Iterables are only iterated until all bindings are assigned.
The rest binding is eagerly evaluated and creates a new array, instead of using the old iterable.
Object destructuring
Basic assignment, assigning to new variable names.
A property can be unpacked from an object and assigned to a variable with a different name than the object property.
Here, for example, const { p: foo } = o takes from the object o the property named p and assigns it to a local variable named foo .
Assigning to new variable names and providing default values
A property can be both
- Unpacked from an object and assigned to a variable with a different name.
- Assigned a default value in case the unpacked value is undefined .
Unpacking properties from objects passed as a function parameter
Objects passed into function parameters can also be unpacked into variables, which may then be accessed within the function body. As for object assignment, the destructuring syntax allows for the new variable to have the same name or a different name than the original property, and to assign default values for the case when the original object does not define the property.
Consider this object, which contains information about a user.
Here we show how to unpack a property of the passed object into a variable with the same name. The parameter value { id } indicates that the id property of the object passed to the function should be unpacked into a variable with the same name, which can then be used within the function.
You can define the name of the unpacked variable. Here we unpack the property named displayName , and rename it to dname for use within the function body.
Nested objects can also be unpacked. The example below shows the property fullname.firstName being unpacked into a variable called name .
Setting a function parameter's default value
Default values can be specified using = , and will be used as variable values if a specified property does not exist in the passed object.
Below we show a function where the default size is 'big' , default co-ordinates are x: 0, y: 0 and default radius is 25.
In the function signature for drawChart above, the destructured left-hand side has a default value of an empty object = {} .
You could have also written the function without that default. However, if you leave out that default value, the function will look for at least one argument to be supplied when invoked, whereas in its current form, you can call drawChart() without supplying any parameters. Otherwise, you need to at least supply an empty object literal.
For more information, see Default parameters > Destructured parameter with default value assignment .
Nested object and array destructuring
For of iteration and destructuring, computed object property names and destructuring.
Computed property names, like on object literals , can be used with destructuring.
Invalid JavaScript identifier as a property name
Destructuring can be used with property names that are not valid JavaScript identifiers by providing an alternative identifier that is valid.
Destructuring primitive values
Object destructuring is almost equivalent to property accessing . This means if you try to destruct a primitive value, the value will get wrapped into the corresponding wrapper object and the property is accessed on the wrapper object.
Same as accessing properties, destructuring null or undefined throws a TypeError .
This happens even when the pattern is empty.
Combined array and object destructuring
Array and object destructuring can be combined. Say you want the third element in the array props below, and then you want the name property in the object, you can do the following:
The prototype chain is looked up when the object is deconstructed
When deconstructing an object, if a property is not accessed in itself, it will continue to look up along the prototype chain.
Specifications
Specification |
---|
Browser compatibility
BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
- Assignment operators
- ES6 in Depth: Destructuring on hacks.mozilla.org (2015)
Basic JavaScript - Assignment with a Returned Value
Tell us whatās happening:
Describe your issue in detail here. what is the mathematic expression of (num + 3) / 5; ??? how come it is processed = processArg(7); ???
Your code so far
(num + 3) / 5;
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36
Challenge Information:
Hey, 7 is the argument of the num parameter. If you work out the expression in the curly braces the return value will be 2. That value is assigned to the function processArg
Call the processArg function with an argument of 7 and assign its return value to the variable processed .
Here youāve called the function and assigned its value to the processed variable. The function value was 2, so the processed value will be the same.
I hope answered what you asked.
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.
- C++ Data Types
- C++ Input/Output
- C++ Pointers
- C++ Interview Questions
- C++ Programs
- C++ Cheatsheet
- C++ Projects
- C++ Exception Handling
- C++ Memory Management
Why Assignment Operator Overloading Must Return Reference?
Operator overloading in C++ allows us to define custom behaviors for operators when applied to user-defined types. One of the most commonly overloaded operators is the assignment operator (=), which is used to assign the value of one object to another. However, when overloading the assignment operator, itās important to ensure that it returns a reference to the object being assigned. But why is this necessary?
In this article, we will learn why the assignment operator must return a reference in C++ when overloading, and what could go wrong if it doesnāt.
Why Must the Assignment Operator Return a Reference?
When overloading the assignment operator in C++ , itās important that it returns a reference to the object being assigned. There are several key reasons for this:
1. Chaining of Assignment Operations
In C++, assignment operations can be chained together.
For example:
To support this chaining, the assignment operator must return a reference to the object being assigned. This allows the operation b = c to return b, enabling a = b to work as expected.
2. Consistency with Built-in Types
For built-in types, the assignment operator in C++ returns a reference to the left-hand operand. To maintain consistency and intuitive behavior for user-defined types, overloaded assignment operators should also return a reference.
3. Avoiding Unnecessary Object Copies
If the assignment operator returned an object by value instead of by reference, it would result in the creation of a temporary object, which is immediately discarded. This unnecessary copying is inefficient and could lead to performance issues, especially for large objects or objects managing dynamic resources.
C++ Program to Demonstrate Properly Overloading the Assignment Operator
The below example demonstartes how to properly overload the assignment operator in C++.
What Happens if Assignment Operator Does Not Return a Reference?
If we overload the assignment operator and return by value instead of by reference, several issues could arise:
- Chained assignments like a = b = c; would not work correctly.
- Returning by value would create temporary objects, leading to inefficiencies.
- The overloaded assignment operator would behave differently from the built-in assignment operator, which could confuse others of our class.
In C++, when overloading the assignment operator, we must return a reference to the current object ( *this ) as it allows for assignment chaining, maintains consistency with built-in types, and avoids unnecessary object copying. By following these best practice, we can ensure that our overloaded operators are efficient, intuitive, and behave as expected, making our C++ programs more robust and maintainable.
Please Login to comment...
Similar reads.
- C++-Operator Overloading
Improve your Coding Skills with Practice
What kind of Experience do you want to share?
Using Javascript and AJAX in the Fetch()API method: returns no values as a response
Good day, I have attempted to follow the post - āReturning Table Values from User Selectionā. My APP does not make use of any forms, but Iāve found that the concepts regarding the use of the Fetch() method make sense for my APP.
I would like the above script to allow me to access the āidā and field attributes to display fetched data from cell values (User Selections) in a separate HTML table.
Side note: When posting code here, enclose the code between lines of ```. This means youāll have a line of ```, then the code, then another line of ```. This forces the code to remain properly formatted. Also, please remove unnecessary and excessive leading spaces on the lines. Having code indented 20+ characters is very difficult to read here. (Iāve taken the liberty of editing your original post for this. Please keep these tips in mind for the future.)
You have posted a block of code, and have identified what you would like to do. What is the issue or problem with the code that you are having?
What error messages are you seeing? (Either in the browser console or on the server?)
Note that we are unlikely going to be able to help you much without knowing the structure of the html from which you are trying to extract data.
Also, this block of lines isnāt going to do what I think you might be wanting it to do. The getElementById is going to retrieve a reference to one html element. Youāre setting the innerHTML attribute of that element multiple times, where each successive assignment will overwrite the previous assignment.
Hi, thanks for you reply. In future I will make sure I leave the entire line after \. Im not quite sure I pick up on the code indented 20+ characters. Should I have each line of code begin at the beginning of each line? Ok, firstā¦ here is the structure of the html from which I am trying to extract the dataā¦
This is the structure of the table I would like to display the data intoā¦
As for setting the innerHTML attribute of the element multiple times should I rather have the following:
The problem I see that I would like to fix first is that despite having been told to setup the API and then using the fetchAPI script - the JSON response does still not come through to populate the table as a cell value. I think I will leave it there and await your response before speaking about some of the other errors that have resulted in the browser. Thank you!!!
Not at the beginning of every line, no. But your original posting had every line indented at least 24 characters, making it effectively unreadable. Your first line should probably start at the beginning of the line, with subsequent lines indented appropriately.
In order to assign values to those individual <td> elements, you either need to provide individual id attributes to every one, or use relative addressing to locate them using the querySelector or use something like getElementsByTagName to iterate over the entire table.
Regardless of the specific function being used, itās up to your JavaScript code to ensure that the right data is put into the proper element.
The alternative to this would be to have the server render that table for you, and return the table as an HTML fragment that replaces the existing table in the HTML.
For that, weād need to see a lot more detail. At a minimum, weād need to see the url definition for the getfirstAssignmentSelected url and the related view. Then weād need to see what data is actually returned, along with any error messages generated on the server or in the browser console.
Hi. Considering that I would like to code some additional charts that archive the selections made related to specific dates I think it might be a good idea to have the server render a tableā¦ then I think the data will be stored and accessible in and from local storage.
Here is the url definition for getfirstAssignmentSelected:
Here is the view for gerfirstAssignmentSelected:
As I wait for your next response I will read up on providing individual id attributes to every element so that I know. As well as relative addressing. As I was saying when I opened the console and looked for JS data that should be returned, there was nothing under āNameā. I believe that this method relies more on fetching data / fields created with Django models than on creating a JSON array for example like one of the map() methods I tried - which confused me because even though I think it is possible to iterate over rows and cells, that reproduced table data as opposed to allowing for a user selection to determine what data populates the table.
If you donāt mind, letās give the HTML fragment a shot, and please do let me know if I understand the functionality there. Thanks
Oh, and in terms of errors that are currently popping up. These arenāt related to this topic I donāt think - they are āGETā errors related to the static files that Iāve been using as a template to design. From my understanding I would need to configure my Apache server correctly to help to fix this anyway.
I donāt see any element named name in the JsonResponse you are creating. Please post what you are receving
Which method? I donāt know what youāre referring to here.
Related Topics
Topic | Replies | Views | Activity | |
---|---|---|---|---|
Forms & APIs | 10 | 1182 | December 29, 2023 | |
Templates & Frontend | 23 | 4092 | August 17, 2022 | |
Templates & Frontend | 4 | 1492 | August 15, 2023 | |
Forms & APIs | 12 | 1630 | January 10, 2023 | |
Forms & APIs | 0 | 94 | May 19, 2024 |
- 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.
assign function return value to some variable using javascript
I have a js function , after doing some business logic, the javascript function should return some result to another variable.Sample code below
Here i want to use like
I want to assign a return value "status" "var response".But the result is 'undefined'.
- Already got the correct wording in your title: return value . But you are not using return in your function ;) – Felix Kling Commented Oct 15, 2010 at 10:33
- Note that usually you don't need to initialize new variables with values if those values are falsy (which an empty string is). You can just write: var response; The value of response will be set to the undefined value in this case (which is also a falsy value). Then later, when you want to check if the value has been set, you can just check if it is falsy or not... – Šime Vidas Commented Oct 15, 2010 at 10:45
- @Felix: i have a ajax call inside the function, it is returning "undefined". any idea? Thanks – Ra. Commented Oct 15, 2010 at 11:14
- 3 Search here on SO about this issue. This is normal. You cannot return a value form an Ajax call, because it is executed asynchronously, i.e. the return statement is executed before the Ajax call finished. You can solve this using callbacks... – Felix Kling Commented Oct 15, 2010 at 11:21
- @Felix: Hi, i made a little change in the code, after success condition, i just include "async :false".... now the code is working fine as expected :) – Ra. Commented Oct 19, 2010 at 7:55
5 Answers 5
In this case, the response variable receives the return value of the function. The function executes immediately.
You can use this construct if you want to populate a variable with a value that needs to be calculated. Note that all calculation happens inside the anonymous function, so you don't pollute the global namespace.
- 6 For the curious, this is called an immediately invoked function express (IIFE). And it is awesome. – Scribblemacher Commented Jun 16, 2017 at 15:33
- 6 Note that the function itself is inside parenthesis (there is an opening parenthesis before the word function ) and that there is an extra () at the end. (It was not obvious to me at first sight) – J0ANMM Commented Jun 16, 2017 at 16:27
- How do I pass parameters using this syntax? – Leonard Niehaus Commented Aug 30, 2019 at 22:42
- @LeonardNiehaus (function(w) { /*ā¦*/ })(window) – Šime Vidas Commented Aug 31, 2019 at 13:05
AJAX requests are asynchronous. Your doSomething function is being exectued, the AJAX request is being made but it happens asynchronously; so the remainder of doSomething is executed and the value of status is undefined when it is returned.
Effectively, your code works as follows:
And then some time later, your AJAX request is completing; but it's already too late
You need to alter your code, and populate the "response" variable in the "success" callback of your AJAX request. You're going to have to delay using the response until the AJAX call has completed.
Where you previously may have had
You should do:
You could simply return a value from the function:
- Its working... but i have ajax call inside, in thats time the result is 'undefined'. Any idea? Please look at the modified sample code. – Ra. Commented Oct 15, 2010 at 11:12
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() .
The result is undefined since $.ajax runs an asynchronous operation. Meaning that return status gets executed before the $.ajax operation finishes with the request.
You may use Promise to have a syntax which feels synchronous.
You can call the promise like this
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 jquery or ask your own question .
- The Overflow Blog
- Scaling systems to manage all the metadata ABOUT the data
- Navigating cities of code with Norris Numbers
- Featured on Meta
- We've made changes to our Terms of Service & Privacy Policy - July 2024
- Bringing clarity to status tag usage on meta sites
- Tag hover experiment wrap-up and next steps
Hot Network Questions
- Why would Space Colonies even want to secede?
- Double and single delta-function potential well energy similarity
- Short story about a committee planning to eliminate 1 in 10 people
- Combination with true strike
- Can someone help me identify this plant?
- Why would luck magic become obsolete in the modern era?
- Why does Air Force Two lack a tail number?
- Returning to France with a Récépissé de Demande de Carte de Séjour stopping at Zurich first
- Will the american customs be suspicious of my luggage if i bought a lot of the same item?
- Density of perfect numbers
- Claims of "badness" without a moral framework?
- Someone wants to pay me to be his texting buddy. How am I being scammed?
- Unstable output C++: running the same thing twice gives different output
- Should I pay off my mortgage if the cash is available?
- Specified data directory does not exist - but it does
- What is a word/phrase that best describes a "blatant disregard or neglect" for something, but with the connotation of that they should have known?
- Can you bring a cohort back to life?
- How do you determine maximum frequency of AD574A 12-bit ADC?
- Are there rules of when there is linking-sound compound words?
- How can I vertically align LEDs in a LaTeX circuit diagram using Circuitikz?
- Colleague reviews a same pull request several times instead of once
- Shift right by half a trit
- A post-apocalyptic short story where very sick people from our future save people in our timeline that would be killed in plane crashes
- How are USB-C cables so thin?
IMAGES
COMMENTS
That's the way the language was designed. It is consistent with most languages. Having a variable declaration return anything other than undefined is meaningless, because you can't ever use the var keyword in an expression context.. Having assignment be an expression not a statement is useful when you want to set many variable to the same value at once:. x = y = z = 2;
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. This allows multiple assignments to be chained in order to assign a single value to multiple variables. ... Return value. The value of y. Exceptions. ... JavaScript does not have implicit or ...
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 which adds two numbers together, then: will call sum function, which ...
This chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more. At a high level, an expression is a valid unit of code that resolves to a value. There are two types of expressions: those that have side effects (such as assigning values) and those that ...
Let's have a go at writing our own functions featuring return values. Make a local copy of the function-library.html file from GitHub. This is a simple HTML page containing a text <input> field and a paragraph. There's also a <script> element, in which we have stored a reference to both HTML elements in two variables. This page will allow you to enter a number into the text box, and display ...
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window.
An assignment operator ( =) assigns a value to a variable. The syntax of the assignment operator is as follows: let a = b; Code language: JavaScript (javascript) In this syntax, JavaScript evaluates the expression b first and assigns the result to the variable a. The following example declares the counter variable and initializes its value to zero:
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.
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 ...
135 1 2 8. 4. 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.
Learn to Code ā For Free
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.
This is made to assign a default value, in this case the value of y, if the x variable is falsy. The boolean operators in JavaScript can return an operand, and not always a boolean result as in other languages. The Logical OR operator ( ||) returns the value of its second operand, if the first one is falsy, otherwise the value of the first ...
function processArg (num) {. return (num + 3) / 5; } // Only change code below this line. processed = processArg (7); 10 Likes. Assignment with a Returned Value Hints Hint 1 Functions act as placeholders for the data they output. Basically, you can assign the output of a function to a variable, just like any normal data.
Tell us what's happening: Hello, I am totally confused. I don't get this topic AT ALL! I copied the "hint" answer, but don't understand what this is all about. I've been matriculating so farā¦but this oneā¦oy vey! Can someone explain this to me in hard core laymen nubie code language, please? Thanks, Cheyena Your code so far // Example var changed = 0; function change(num ...
Unpacking values from a regular expression match. When the regular expression exec() method finds a match, it returns an array containing first the entire matched portion of the string and then the portions of the string that matched each parenthesized group in the regular expression. Destructuring assignment allows you to unpack the parts out of this array easily, ignoring the full match if ...
This JavaScript exception invalid assignment to const occurs if a user tries to change a constant value. Const declarations in JavaScript can not be re-assigned or re-declared. Message: TypeError: invalid assignment to const "x" (Firefox) TypeError: Assignment to constant variable. (Chrome) TypeError: Assignment to const (Edge) TypeError: Redeclara
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 ...
Hey, 7 is the argument of the num parameter. If you work out the expression in the curly braces the return value will be 2. That value is assigned to the function processArg. Call the processArg function with an argument of 7 and assign its return value to the variable processed.. Here you've called the function and assigned its value to the processed variable.
Prerequisite: Operator Overloading The assignment operator,"=", is the operator used for Assignment. It copies the right value into the left value. Assignment Operators are predefined to operate only on built-in Data types. Assignment operator overloading is binary operator overloading.Overloading assignment operator in C++ copies all values of one
Good day, I have attempted to follow the post - "Returning Table Values from User Selection". My APP does not make use of any forms, but I've found that the concepts regarding the use of the Fetch() method make sense for my APP. <script> selectAssignment = document.getElementById('assignments'); selectAssignment.addEventListener('change', onChange); function onChange(e) { let ...
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().
This site requires JavaScript to be enabled.