How do I call a function within an IIFE expression - javascript

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.

Related

Can you use parent function variables inside a returned function in javascript?

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());

JavaScript Functions , return undefined

Hello Everyone hope you all doing great ,
this is my code , function with name and callback
taking the name to callback function to make return the name and console.log it
if i
function doSomething(name,callback) {
callback(name);
}
function foo(n) {
return n;
}
var val = doSomething("TEST",foo);
console.log(val);
i got undefined .
if i
function doSomething(name,callback) {
callback(name);
}
function foo(n) {
console.log(n);
}
var val = doSomething("TEST",foo);
that works fine and console.log the TEST name .
So why the return not working ?
thanks
Your doSomething() function doesn't return anything, which means an assignment using it will be undefined. But, that's not really the problem here.
The underlying problem is that you seem to be mixing two different data processing patterns here: if you're writing purely synchronous code, then use returning functions (which immediately return some value). If you need asynchronous code, then use a callback (which will "eventually" do something). Mixing those two patterns is a recipe for problems and frustration:
Either:
don't name your function a "callback", and have it return its processed value, or
make the callback responsible for doing whatever it is you were going to do with val.
Case 1:
function doSomething(data, processor) {
return processor(data);
}
function passThrough(v) { return v; }
var val = doSomething("test", passThrough);
// immediately use "val" here in for whatever thing you need to do.
Case 2:
function doSomething(data, callback) {
// _eventually_ a callback happens - for instance, this
// function pulls some data from a database, which is one
// of those inherently asynchronous tasks. Let's fake that
// with a timeout for demonstration purposes:
setTimemout(() => callback(data), 500);
}
function handleData(val) {
// use "val" here in for whatever thing you need to do. Eventually.
}
doSomething("test", handleData);
And if you want to go with case 2, you really want to have a look at "Promises" and async/await in modern Javascript, which are highly improved approaches based on the idea of "calling back once there is something to call back about".
2021 edit: a third option since original writing this answer is to use the async/await pattern, which is syntactic sugar around Promises.
Case 3:
async function doSomething(input) {
// we're still _eventually_ returning something,
// but we're now exploiting `async` to wrap a promise,
// which lets us write normal-looking code, even if what
// we're really doing is returning a Promise object,
// with the "await" keyword auto-unpacking that for us.
return someModernAsyncAPI.getThing(input);
}
function handleData(val) {
// ...
}
async function run() {
const data = await doSomething("test");
handleData(data);
}
run();
function doSomething(name,callback) {
callback(name);
}
function foo(n) {
console.log(n);
return n;
}
var val = doSomething("TEST",foo);
Take a look at above code. When you call doSomething, which internally executes foo it prints on the console because thats what console.log is for. However, after this statement it returns n as well which then is received in doSomething. But its not being returned. To put it simply, what you are mainly doing is
function doSomething(name,callback) {
const returnValue = callback(name);
}
If you call the above method, it will return undefined. To make it return correct value, you have to call "return returnValue". Similary you have to say
return callback(name)
Hope this helps.
Happy Learning
Inorder to assign the returning value/object of a function(in this case doSomething, it should have a return statement. Else the function returns nothing, so when you assign that to val, it is still undefined.
So you modify your code like this:
function doSomething(name,callback) {
return callback(name);
}
function foo(n) {
return n;
}
var val = doSomething("TEST",foo);
console.log(val);
undefined is implicitly returned if you don't have a return in your function.
when you call var val = doSomething("TEST",foo), you are aligning the return value of doSomething to val, which is undefined.
function doSomething(name,callback) {
return callback(name);
}
function foo(n) {
return n;
}
var val = doSomething("TEST",foo);
console.log(val);

javascript function hoisting does not works

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.

What is the point of the return in Javascript?

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!

Check for function called

Just wondering if there is anyway to fire some code when a function is called, without adding the code to the function, for example:
function doSomething(){
//Do something
}
//Code to call when doSomething is called
You can wrap the function :
(function(){
var oldFunction = doSomething;
doSomething = function(){
// do something else
oldFunction.apply(this, arguments);
}
})();
I use an IIFE here just to avoid polluting the global namespace, it's accessory.
Well, yes, it's not actually hard to do. The crucial thing is that a function's name is just an identifier like any other. You can redefine it if you want to.
var oldFn = doSomething;
doSomething = function() {
// code to run before the old function
return oldFn.apply(this, arguments);
// code to run after the old function
};
NB that it's better to do oldFn.apply(this, arguments) rather than just oldFn. In many cases it won't matter, but it's possible that the context (i.e. the value of this inside the function) and the arguments are important. Using apply means they are passed on as if oldFn had been called directly.
What about something like:
function doSomething(){
doSomething.called = true;
}
//call?
doSomething();
if(doSomething.called) {
//Code to call when doSomething is called
}
I know you said you don't want to modify the original function, but consider adding a callback. Then you can execute code based on different results in your function (such as onSucess and onError):
function doSomething(onSuccess, onError){
try {
throw "this is an error";
if(onSuccess) {
onSuccess();
}
} catch(err) {
if(onError) {
onError(err);
}
}
}
Then, when you call doSomething, you can specify what you want done with inline functions:
doSomething(function() {
console.log("doSomething() success");
}, function(err) {
console.log("doSomething() error: " + err);
});

Categories