This question already has answers here:
Why do results vary based on curly brace placement?
(6 answers)
Closed 9 years ago.
var calculator = function ()
{
function abc() { return (2+3); }
return {
addFun: abc
}
}();
var calcu = function () {
function abc() { return (3+4); }
return
{
addFun: abc
}
}();
$(document).ready(function () {
alert(calculator.addFun());
**alert(calcu.addFun());**
});
What is difference between calculator and calcu function? calcu function gives error when it execute.
Difference is only that curly bracket is next line in "calcu". It is work fine if I remove next and put curly bracket with "return" keyword.
Please explain why so?
It's being parsed as this:
return; // returns undefined
// a block:
{
addFun: abc // syntax error!
};
because of automatic semicolon insertion.
Change it to:
return {
addFun: abc
};
It's called automatic semicolon insertion:
When a continue, break, return, or throw token is encountered and a LineTerminator is encountered before the next token, a semicolon is automatically inserted after the continue, break, return, or throw token.
Since there's a newline right after your return statement, a semicolon is inserted automatically, turning your code into:
return;
{
addFun: abc
}
Return is a tricky keyword in JavaScript. In the first example, you are returning an anonymous object to the calculator function, and in the second example you are returning no values. JavaScript will interpret the second function like this:
var calcu = function() {
function abc() ...
return; // return undefined
{
addFun: abc
}
Notice the semi colon is interpreted after the return keyword and thus the calcu function will return nothing.
return
{
addFun: abc
}
This is wrong because JavaScript would execute return and will get out.
This should be
return {
addFun: abc
}
Have a look at linting tools such as jshint to avoid this and many other errors, here is it's output:
What happens is that this section:
return
{
addFun: abc
}
is being interpreted as two statements, a return void (the function returns void immediatelly) plus an object expression containing addFun that is not assigned to anything.
Related
Here's the function code:
function TestFunction(number){
return function(e){
return `${number}`;
}
}
When I use it on google's devtools command line it returns:
function(e){
return `${number}`;
}
So it looks like the function returned is not created with the number I give to TestFunction, instead it takes the string just like it was written. I have tried to use concatenation instead of interpolation but still not working. What can I do?
There is indeed a closure around the second function, so it will have memory of what num is.
function a(num) {
return function b() {
return `${num}`;
}
}
const c = a(6);
console.log(c());
Just started out learning js and using the book Javascirpt an Absolute Beginner's Guide. Question is from an example in the book:
var awesomeSauce = (
function () {
var secretCode = "Zorb!";
function privateCheckCode(code) {
if (secretCode == code) {
alert("You are awesome!");
} else {
alert("Try again!");
}
}
// the public method we want to return
return {
checkCode: privateCheckCode
};
})();
Question is how do I go about to call this code?
awesomeSauce("Zorg!");
doesnt work and neither does
awesomeSauce().privateCheckCode("Zorg!");
awesomeSauce.checkCode("Zorg!");
The IIFE returns an object with the checkCode property, that property is the (private) function.
The point of the IIFE is that this scopes the variables and functions within, so that they are not accessible from outside (e.g. privateCheckCode and secretCode exist only inside the IIFE).
Think of the returned object as an "export" of selected values or functionality.
var awesomeSauce = (
function () {
var secretCode = "Zorb!";
function privateCheckCode(code) {
if (secretCode == code) {
alert("You are awesome!");
} else {
alert("Try again!");
}
}
// the public method we want to return
return (
privateCheckCode
);
})();
awesomeSauce('Zorb!')
hey i don't know much but i happened to solve this: return statement return an expression not a code block. just go through the code i guess you will understand
Agree with Lucero's answer
1) The IIFE gets executed
2) result of the execution gets assigned to awesomeSauce
So what is the result of execution ?
It is whatever the function returned, below code
return {
checkCode: privateCheckCode
};
In this case, it returns an object with a property named "checkCode" which refers to inner function "privateCheckCode".
In short, it becomes,
awesomeSauce = {
checkCode: privateCheckCode
};
Therefore, you can call your function like this awesomeSauce.checkCode("Zorb!");
You can call it with console.log(awesomeSauce.checkCode('Zorb!'));
as the iife returns an object which has checkCode key and the privateCheckCode as the value.
function test(flag){
if (flag) {
return function test1(){console.log(1)}
}else{
return function test1(){console.log(2)}
}
}
test(true)()
test()()
it log 1 and 2,why not double 2?
how does this works
my english is not very good, thank you
this also works with 1 and 2
function test(flag){
if (flag) {
function test1(){console.log(1)}
return test1
}else{
function test1(){console.log(2)}
return test1
}
}
test(true)()
test()()
The function in this line:
return function test1(){console.log(2)}
Is not a function declaration. It is a named function expression, because it is part of a statement.
Function expressions are not hoisted. Only function declarations are hoisted, like this:
function test(){
return test1;
function test1() { console.log(1); }
function test1() { console.log(2); }
}
test()();
Edit: Regarding the question you added after the fact, function declarations inside conditional expressions have undefined behavior and you can see different results depending on your JavaScript engine. Functions inside if-else statements may not be hoisted to the top of the scope, and you should not put function declarations inside conditional expressions. More about this
In the first call test(true)() it goes through:
if (flag) {
return function test1(){console.log(1)}
}
because the flag has value true.
In the second call test()() it goes through the else path:
else{
return function test1(){console.log(2)}
}
because in that instance value of flag is undefined and it evaluates as false.
You can get an idea about truthy and falsy using these links.
Hope you got the idea here. Please let me know if you have any questions.
This question already has answers here:
Can anyone explain why linebreaks make return statements undefined in JavaScript? [duplicate]
(4 answers)
Closed 7 years ago.
I have the code:
function func1(){
return
array.map(function(el){
return el.method();
});
}
function func2(){
var confused =
array.map(function(el){
return el.method();
});
return confused;
}
Why func1 return undefined while func2 return good value (that i need)?
Sorry for my english.
Internally in JS engine first example looks like this,
function func1() {
return;
array.map(function(el){
return el.method();
});
};
that's why you get undefined, don't add new line after return, because return statement followed by a new line tells the JS intepreter that a semi colon should be inserted after that return.
function func1() {
return array.map(function(el){
return el.method();
});
};
I've recently been learning javascript and came across the return statement or whatever it is. I've watched tutorials on it and I still don't get the point of it. Do I ever need it for anything and can someone please explain in detail what it does? Thanks
The return statement has multiple uses:
1) Return early from your function before the end of the function body. This is often within a branch of the code as in:
function whatever()
// do some things
if (err) {
console.log(err);
return err;
}
// other code here that will not execute if there was an err
}
2) Return a specific value back to the caller as in:
function add(a, b) {
return a + b;
}
var sum = add(3,4);
console.log(sum); // will show 7
The return statement in javascript can be used by itself to just exit the current function call and not return a specific value or it can be used to return a specific value.
If no return statement is present in a function, then the function will execute to the end of the function body and will return automatically at the end of the function body.
The only point of it is to send a value (string, number, or other values) from your function so that is can be used outside the function. Instead you can use global variables but that takes up more code, so it's a shortcut instead.
jfreind00 above said that you can use it to branch off early but that's what break. Here is the syntax:
function HiThere(something) {
if (something === true) {
break;
}
alert("Hi");
}
In this case, if something is true, then exit the function, if not then say hi.
Return would be like this:
function HiThere(something) {
if (something === true) {
return "Value to return: " + something;
}
alert("Hi");
}
In this case, if something is true, then exit the function and return Value to return: true, if not then say hi but don't return anything back.
Here's the most common use of the return statement:
document.getElementById("demo").innerHTML = myFunction(5,3); // Call a function
// to set the "demo" element to the value of: 5 * 3
function myFunction(a,b) {
return a * b;
}
<p id="demo"></p>
Use it to return a value. Your value could be "Yes", "false", "hello world" or "eat dirt." You can then run certain code based on the returned value.
Hope this helps!