alert function in javaScript - javascript

Can someone help me to better understand why the second alert box appears with 'undefined' in it? When I call the function without alert function I don't see it.
var n = 1; // global scope
function one() {
alert(n);
}
alert(one());

alert(one()) alerts the return value of the function one. That function does not return a value, so its return value is undefined.
If you want to change the value of the second alert, you need to use return <value> from within one.
var n = 1; // global scope
function one() {
alert(n);
return 42;
}
alert(one());

Related

How can I understand the following javascript code which contains a function within function

I am learning javascript, and I am not able to understand the following piece of code.
const increment = (function() {
return function test(number, value) {
return number + value;
};
})();
console.log(increment(5, 2)); // output 7
My attempt at understanding
I removed the () on line 5, and then ran the following code.
const increment = (function() {
return function test(number, value) {
return number + value;
};
});
console.log(increment(5, 2));
This returns the output test(number, value) which I can understand. The increment variable points to the function test.
However, I don't understand how adding () passes the arguments (5,2) to test?
Said another way, if the output of the second code block is test(number, value), the output after adding () is test(number,value)() which seems meaningless.
It calls self-invoking.
If you write function like that (function foo(){})() then foo will be immediately called and result will be returned.
So as result in increment you have test function.
And then you call it with arguments.
increment(5, 2) // test(5, 2)
Here is some info about that
() at the end of the function immediately calls it - it's called IIFE ("Immediately invoked function expression").
When calling it with increment(5, 2) - you are actually calling the test function that is returned by the IIFE.
Your question is regarding the Javascript Immediate Functions.
First, we need to know what a function is, which is basically a block of code that returns a value.
And to declare a function in Javascript, one way is this:
function a() {
return "in this case, a string";
}
If we do:
const variable = function () {
return "in this case, a string";
};
console.log(variable); // Function
But Immediate Functions, as the name implies, are functions that are executed immediately after being defined, so, the value that the function returns is the value that will be given to the variable:
const variable = (function () {
return "in this case, a string";
})();
console.log(variable); // "in this case, a string"
About removing parentheses:
// This is
const increment = (function() {
return function test(number, value) {
return number + value;
};
});
// ...the same as this
const increment = function() {
return function test(number, value) {
return number + value;
};
};
We use parentheses just to isolate this expression (which is the function) and execute it right afterwards:
// Now the parentheses make sense,
// because we need it to execute the function right after it is defined
const increment = (function() {
return function test(number, value) {
return number + value;
};
})();
Read more about Immediate Functions here

What does Return do in here?

I have problem with 'return' means in this code.
1.
function func4() {
var str = "function works.";
console.log(str);
}
func4();
2.
function func4() {
var str = "function works.";
return str;
}
var value = func4();
console.log(value);
Both of them, their result is 'function works.'.
I know that return used for exit function but I'm still confuse when I have to use return exactly.
Sorry about my super basic question :(
As far as I understand 'return' assigns value to a function and returns it, so you're displaying function's value. In the first case you are just simply invoking a function to display a string.
Let's analize this two scenarios:
You have a function that initialize a variable with a predefinided value, and then, you log the value. Then, outside the function you execute it
You have the same variable but with the difference that instead of loggin the value inside the function, you returned it from it. So you can initialize the funcion and store the value on another variable var value = func4();.
Let me try to explain it with some requirements.
I want a function which returns me some data instead of passing a variable and updating the variable in function.
You call a function and it is always best to test negative scenarios first. So in case of negative scenario you can return it from there it self.
In your second case if you see you are getting a value from that function and then printing it. Same thing you can not do using first function.
Always there are workarounds for everything. In the end it depends on your need and what is best suited for that situation.
Both of those functions don't equal the same thing, but they do log the same string.
func4() in #1 is equal to undefined, because it returns nothing.
func4() in #2 returns (gives back) the value "function works.", a string, which is then given to console.log outside of the function.
function func1() {
var str = "function works.";
// console.log(str);
}
func1();
function func2() {
var str = "function works.";
return str;
}
// console.log(func2());
console.log(func1() === undefined);
console.log(func2() === 'function works.');
If you want to use the func4() value for further calculations without calling it again, then you would return {value}.
For e.g
function func4(userInput) {
return userInput % 2 == 0;
}
var response = func4(userInput);
if(response == true) {
console.log('user entered an even number');
} else {
console.log('user entered a odd number');
}
// from here you can use the value of response n times without calling the function again.
Whereas, if you don't return then you will have to call the function x number of times whenever you want to re-user the response of it.
function func4(){
var str = "function works.";
return str;
}
var value = func4();
console.log(value);
//here return means you are returning the value of variable 'str'.
You can find the details here.
https://learn.microsoft.com/en-us/cpp/c-language/return-statement-c?view=vs-2019#:~:text=A%20return%20statement%20ends%20the,value%20to%20the%20calling%20function

Javascript Closure Return Function

I am trying to learn about closures in javascript and I came across the following example:
function counter() {
var count = 0;
return function() {
alert(count++);
}
}
var count = counter();
count();
count();
count();
Which makes sense to me, my question is, why doesn't this work?
var count = function() {
var count = 0;
return function() {
alert(count++);
}
};
count();
count();
count();
To me it seems like it should be the exact same thing but maybe I'm just missing something obvious, please assist.
In order for your second method to work, you will need to call the returned function like this:
var count = function() {
var count = 0;
return function() {
alert(count++);
}
};
count()();
However, doing this, your count number will not increase because it is not being stored anywhere like in the first example, where the variable count holds the function.
So if you want to retain the value of count, use the first method where you say var count = counter()
Hope that clears things up!
I'll try to give a nice explanation right in your code:
function counter() {
var count = 0;
// By calling the function counter (adding a '()' after its name) you are returning a brand new anonymous function
return function() { // **Reference 1**
alert(count++);
}
}
// Here, the count variable is actually the anonymous function you returned in the **Reference 1**
var count = counter();
// In this line, you are calling the anonymous function (adding the '()' after its new name 'count')
count();
The explanation above explain why this works. Because, first you called a function which returned an anonymous function and assigned it to the variable count. Then you called that function by adding the '()' after its name, which executes the alert(count++)
Now, why the other example does not work? I guess it's pretty obvious now:
var count = function() {
var count = 0;
return function() { // **Reference 2**
alert(count++);
}
};
// Here you are calling the count function which returns the anonymous function in the line **Reference 2**.
count(); // So, long story short, this call only returns the anonymous function.
You should try to add a second '()' after it: count()();. This should work as well, because the first '()' returns the anonymous function, and the second one, executes the anonymous function returned.
Hope this helps!
Before you can use the closure, you have to call the outer function to create the closure and get the inner function that is returned and then retain that return result that you can then call subsequent times to use the closure. So, in your second example, you have to call count() and retain it's return result and then use that return result for subsequent calls.
Your second example will work if you change it to this (which looks pretty much the same as the first example):
// log output for purposes of the snippet
function log(x) {
var div = document.createElement("div");
div.innerHTML = x;
document.body.appendChild(div);
}
var counter = function() {
var count = 0;
return function() {
log(count++);
}
};
// get the inner function and create the closure
var count = counter();
count();
count();
count();
As you can see this only differs from your first example in that counter is a function expression instead of a function definition. Other than the timing of when counter is defined, the second code example is no different and thus the implementation needs to be the same.

avoid .slice is not a function (javascript)

so i have a variable which as this point has a static definition, i want it to get now the value dynamically from an if-else statement but the above mentioned error pops out:
var x = [{a:b},{c:d},{e:f}]
and i want to change it to get the value from a function:
var x = function(){
if(true){
return [{a:b},{c:d},{e:f}]
}else{
return [{f:g},{h:i}]
}
}
But I get an error x.slice is not a function
Can what am i doing wrong? Looked around but cant manage to fix this... isn't it possible?
x is a function, so you're trying to call .slice() on a function. You want to call x() and use the return value, then slice that:
x().slice(1);
x is a function so it does not have slice you should run it before
var x = (function(){
if(true){
return [{a:b},{c:d},{e:f}]
}else{
return [{f:g},{h:i}]
}
})()

why the code doesn't alert Worky-worky?

var a = function() {
function someSetup(){
var setup = 'done';
}
function actualWork() {
alert('Worky-worky');
}
someSetup();
return actualWork;
}();
why the above code doesn't alert Worky-worky?it shows undefined.thank you
Because you only return the function, not call it.
Perform a(); after this code execution, this will call the function that's returned by anonymous self-executing function, thus actualWork.
you are trying to return a function that has no return type (actualWork()).
It doesn't do the alert() because you didn't call the function properly.
actualWork()
return actualWork; is actually returning a variable, but because you didn't assign anything to that variable you're getting undefined back.
should do the trick.

Categories