Javascript assign variable to alert - javascript

I am wondering Can you assign a variable to alert ? what does it really mean and do ? For example,
var a = alert('test');
I tried it out, and the alert pops up as soon as the page loads where variable a remains 'undefined' when I call it. Aren't we suppose to make it an anonymous function with the alert inside like
var a = function(){ alert('test'); }
If we want to trigger an alert on something? Why does javascript allow you to do that?

var a = alert('test');
Think of this statement like any other variable assignment. In order to perform the assignment, first the right-hand side is evaluated. In this case it's a function call, so the function is called and its return value is obtained. In alert's case, the return value is undefined. It doesn't return anything.
Then the return value is assigned to a, so a ends up with the value undefined.
As a side effect of the statement, an alert message is displayed. That happens as a consequence of calling alert() and getting its return value.
function foo(x) {
return x * 2;
}
var a = foo(3);
This code is structurally similar to the alert call, and would result in a being 6. But then alert() doesn't return a value. It's more like this:
function bar(x) {
return;
}
var a = bar(3);
Now a is undefined.

var a = alert('test');
This says to execute alert('test') and assign the return value from that function to a variable named a.
This would be no different than:
var max = Math.max(1,2,3,4);
where max would end up with the value 4 in it as the return value from executing Math.max(1,2,3,4).
var a = function(){ alert('test'); }
This says to declare an anonymous function and assign that function object to the variable a. Since the function is just declared, it is not executed at this time. You can execute it in the future with a().

You commented:
I am just wondering why javascript allows we to do that if it doesn't really means anything
Well, JavaScript (and any other language, including English) allows you to do a lot of stuff that does not mean anything, as long as the syntax is valid. For example, the snippets bellow also mean nothing:
var a;
a = a; // so what?
function something() { /* nothing */ }
var b = something(); // very similar to your example!
Wouldn't it be less consistent if you could assign from some functions, but not from others? If the language were typed, that would produce an error, but since it's not, what's the problem with it? If they don't return a value, their return is undefined, and nothing breaks if you try to assign that to a variable. So you can make functions that sometimes return something, sometimes not. That can be an advantage if used wisely. It's a feature, not a problem with the language.

If you do:
var a = function(){ alert('test'); }
You can then do:
a();
since you've defined an anonymous function..
alert is a function so you can't assign anything to it, per se.
If you want something to pop up if a variable has a value, you could do something like -
$(document).ready(function() {
if (someVar != undefined) {
alert(someVar);
}
});

Related

When and when not to use 'return' keyword in a funciton?

I have learned in "Function section" of the Javascript course in Codecademy that: to call a function, we have to use 'return' keyword inside the function. But in the "Array section" of the Javascript course found a function can be called without using 'return' keyword inside that function. Can anyone explain when I must use 'return' keyword inside the function and when it is optional?
I am attaching the code snippet for Your reference.
const flowers = ['peony', 'daffodil', 'marigold'];
function addFlower(arr) {
arr.push('lily');
}
addFlower(flowers);
It is not necessary that function must return any value.
When you not required anything from the function then you don't require to return anything. This function called void function.
If you require some value from function the you must return it.
The return keyword is used only to get back some value from the function to the caller so that the value can be used later. In case, if you don't want to use any value from the function, you can omit the return statement.
In the case of objects as a parameter, if that object itself is changed, then it will change the original copy which was passed as well. So, at that time also, no need to return that object from the function.
With the return statement you actually return a value to the caller. For example:
function add(a, b) {
return a+b;
}
var c = add(5,7);
If you have a function that just performs a task without a return value you do not use the keyword. E.g.:
function sayHello() {
console.log('Hello');
}
sayHello();
Note: A return statement ends the function; statements after the return will not be executed.
In fact, there might be a need for returning a value, just like Array.prototype.push() is doing it. Please see the documentation of MDN Web Docs.
function addOneFlower(flowers) {
const newFlower = "Bellflowers";
return flowers.push(newFlower);
}
const flowerArr = [];
let sizeOfFlowerArr = addOneFlower(flowerArr);
// sizeOfFlowerArr starts with 1
sizeOfFlowerArr = addOneFlower(flowerArr);
// sizeOfFlowerArr increased to 2
Use return when you might want to transfer information from inside the function directly to the caller. For example, maybe a caller of addFlower would want to know the name of the flower that was added. Then you would probably have something like
const addedFlower = addFlower(flowers);
This assigns the return value of addFlower to the addedFlower variable. But for that to work, addFlower should return something, eg:
function addFlower(arr) {
arr.push('lily');
return 'lily';
}
If you don't ever need to transfer information directly from inside the function to the caller, then all invocations of the function should be in a standalone line, like
addFlower(flowers);
and there's no need (or sense) for addFlower to return anything.
Note that the caller may sometimes want information that the function returns, but sometimes a caller may not care about it. But the function may not know which, so it should return regardless, and the caller of the function can use the resulting expression if it wants, or the caller can ignore it. Eg, in the same script, there might be one line like
const addedFlower = addFlower(flowers);
and another like
addFlower(flowers); // Don't care about the return value
In this case, addFlower should be returning something regardless, leaving it completely up the caller to do something with the result.
The function when called will run till it reaches a return statement, or the end. If you are using a function with return value, you need to have a return statement in your function definition.
But if you are using a function with no return statement and it can run till the end of the function, than you don't have to have a return statement in the function definition. For example:
function helloWorld() {
console.log('Hello World');
}
the simple example I can give you is this.
let say you have some unknown numbers you want to calculate when the user gives you an input.
for example, you ask your users when he/she was born to calculate his/her age.
function calcAge(yearBorn){
var age = 2019 - yearBorn;
return 'hello user your age is ' + age;
}
calcAge(1993);
when the user gives you the year she/he was born, it will be passed to the yearBorn parameter and will be calculated against the current year. but to use it, you should return it. if you don't return it you will get 'undefined', when you call the function. You have probably seen the console.log() function previously. it is used only on the dev tool in the browser for development purposes. if you want to use the end result from that function, you should use the return keyword then you will get the calculated age instead of 'undefined'! this has something to do with function scope. if you declare the age variable outside of the function and reassign it again in the function, you can probably use the age without the return statement like below.
var age2;
function calcAge2(yearBorn){
age2 = 2019 - yearBorn;
}
When you call it, since the age2 is declared outside of the function, you will be able to access it from the global scope. even if you didn't return it, the function call will update the age2 variable based on the calculation. but declaring a variable in the global scope is not a good practice.
in your example, you have already declared the variable outside of your function.
with const flowers = ['peony', 'daffodil', 'marigold'], you are only pushing additional items in your array by calling the function. if you had declared your flowers array inside the function like bellow, though it is not the best example
function addFlower() {
const flowers = ['peony', 'daffodil', 'marigold'];
flowers.push('lily');
return flowers;
}
then you have to use the return statement to return the value of the array to use it later.
in your case, you are just adding the items in your pre-existing array that was declared in the outer scope.
you don't have to use return if your intention is not to return the value from the function local scope.
since you declared your variable outside of the function, you can update those values without a return statement like you did. but if you want to return a value from a function to be used, you should use the return statement.
check the two examples below. copy them and play around with them in the console.
On the first one since I declared the variable sum inside the function (in the local scop), I have to use the return statement to get the value that is calculated when I call the function. otherwise, the function call will give me undefined value;
function add(x, y){
let sum = x + y;
return sum;
}
but on the second one, the sum variable is declared outside of the function in the global scope. all I am doing when I call the function is updating the pre-existing variable sum. because of that, I don't need to use the return statement here
let sum;
function add(x, y){
sum = x + y;
}
My advice to you, the more you learn about javascript, the dot will connect for you. just keep learning. I have been there. sometimes it feels like nothing makes sense. trust me the dots will connect as you learn more.

Get variable value of a function without setting it globally

Is it possible to get a variable value inside a function without having to set it globally?
I know this is possible:
var testvalue;
function setTestValue(){
testvalue = 30;
}
if you console.log this outside the setTestValue function you will get: 30. Which is clear.
But is there also a possibility to have the same effect but without a global variable?
function setTestValue(){
var testvalue = 30;
}
console.log(testvalue); // will print undefined
The reason why I want this is because I can not change the Javascript file where this function is created. I can only read it and not write it so I need it a workaround.
PS. It might be that this question is already been aksed on stackoverflow but I could not really find it. So if there is, please provide the links to that question.Thanks!
This works (if you don't have var keyword before the variable in the function )
function foo() {
bar = 10; // variable without var comes under window scope so you can access them outside fuction
}
foo();// you have to call the function to set its value
alert(bar) // window.bar also gives 10
why not returning the var in the function:
function setTestValue(){
var testvalue;
do whatever to assign value
return testvalue;
}
console.log(setTestValue());

how do you pass an instance function to an outside function?

let's say I have I have the following in a file called file1.js:
//constructor
function Blah(){
this.string = "hello there agent ";
}
//'method'
Blah.prototype.greeting = function(num){
return this.string + num;
}
Then in a file called file2.js I then have this:
function combine(num,funct){
return funct(num);
}
And then finally, in an html file called file3, I have this:
var bond = new Blah();
document.write(combine(007,bond.greeting));
I am actually getting into the "greeting" method, but for some reason, the return value, instead of being a string, winds up not being NaN. Any idea why? the greeting() method seems to be ran at the proper time. However, despite that, 007 seems to be getting interpreted as NaN anyway. Again, any suggestions as to what could be causing this?
Thanks a bunch in advance
First, depending on how you call the greeting method, the this value will be different. If you call it like bond.greeting(num) then this will be bond. If you call it like funct(num), where funct is bond.greeting, then this will be the global object. You need to bind this permanently when passing the function along, to maintain its value no matter how you call the function.
Second, 007 === 7. If you want to print out 007 literally, then you should use a string:
combine('007', bond.greeting.bind(bond));
Remember, this depends on how the function gets called, it is dynamic, and resolved an runtime, unless you bind it previously, like we did above.
You're experiencing the special characteristics of the this keyword.
Basically, this resolves to whatever you call a function from. In your case, you're calling it from the global scope from through func(), which makes this == window. (Calling it through bond.greeting() makes this == bond.)
To resolve, this either bind the function or force the resolution:
// note that this method requires a shim for IE 8 and older
document.write(combine(007,bond.greeting.bind(bond)));
or
function combine(num, obj, funct){
// since funct is being called from obj, `this` == obj within the function
return obj[funct](num);
}
document.write(combine(007,bond, 'greeting'));
The problem you have is when you pass the function as argument, it is passed by value, and then you loose the reference to the object who has the element string = "hello there agent "; and when the function is executed, it executes "this.string" which doesn't exist inside the function, it returns undefined. It's a scope issue.
The solution to make it work good, is to pass the reference which is the object bond
function combine(num,obj){
return obj.greeting(num);
}
combine("007",bond); // returns "hello there agent 007"
1) NaN is "Not a number" error. Try encapsulating 007 in quotes
2) Do you need file2.js or could you do without it?
var bond = new Blah();
document.write(bond.greeting("007"));

Extra parentheses on function [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What do parentheses surrounding a JavaScript object/function/class declaration mean?
What does this “(function(){});”, a function inside brackets, mean in javascript?
A Javascript function
I encountered markup similar to this:
var something = (function(){
//do stuff
return stuff;
})()
document.ondblclick = function(e) { alert(something(e)) };
I don't understand the opening ( and closing )() in the something variable.
Could you explain the difference to writing it like this?
var something = function(){
//do stuff
return stuff;
};
Thanks!
It's probably easier to understand if you leave the redundant parens out because they serve no purpose:
var something = function() {
return 3;
} // <-- a function.
(); // now invoke it and the result is 3 (because the return value is 3) assigned to variable called something
console.log(something) //3 because the function returned 3
var something = function() {
return 3;
}; // a function is assigned to a variable called something
console.log(something) //logs the function body because it was assigned to a function
console.log(something()) //invoke the function assigned to something, resulting in 3 being logged to the console because that's what the function returns
(function(){ ... }) is a (anonymous) function expression, you could e.g. assign that value to a variable.
The brackets behind it will immidiately execute the function expression, resulting in the return value of the function (in here: stuff). The construct is called IIFE.
When stuff is a function (which I assume, because you invoke something lateron), this is called a closure - the returned function (stuff, assigned to something) still has access to the variables in the execution context of that anonymous function.
On the question what it does, read all the comments and other answers. They are absolutely right.
Why would you want to use it? You find this pattern very often when using closures. The intent of the following code snippet is to add an event handler to 10 different DOM elements and each one should alert it’s ID attribute (e.g. “You’ve clicked 3″). You should know that if this was your actual intent, then there is a much easier way to do this, but for academic reasons let’s stick with this implementation.
var unorderedList = $( "ul" );
for (var i = 0; i < 10; i++) {
$("<li />", {
id: i,
text: "Link " + i,
click: function() {
console.log("You've clicked " + i);
}
}).appendTo( unorderedList );
}
The output of the above code may not be what you first expect. The result of every click handler will be “You’ve clicked 9″ because the value of i at the point the event handler was fired is “9″. What the developer really wanted is for the value of i to be displayed at the point in time the event handler was defined.
In order to fix the above bug we can introduce a closure.
var unorderedList = $( "ul" ), i;
for (i = 0; i < 10; i++) {
$("<li />", {
id: i,
text: "Link " + i,
click: function(index) {
return function() {
console.log("You've clicked " + index);
}
}(i)
}).appendTo( unorderedList );
}
You can execute and modify the above code from jsFiddle.
One way to fix the above code is to utilize a self-executing anonymous function. That is a fancy term that means we are going to create a nameless function and then immediately call it. The value of this technique is that the scope of the variable stays within the function. So, first we will surround the event handler content in a function and then immediately call the function and pass in the value of i. By doing that, when the event handler is triggered it will contain the value of i that existed when the event handler was defined.
Further reading on closures: Use Cases for JavaScript Closures
All of the answers were good, but I think the simplest answer has been skimmed over:
var something = (function(){
//do stuff
return stuff;
})()
After this code executes, something becomes stuff. The function that returned stuff is executed before something is assigned.
var something = function(){
//do stuff
return stuff;
};
After this code executes, something is a function which returns stuff. The function that returns stuff was never executed.
Check the JavaScript FAQ section, too: Here are some pretty good explanations and examples
Ok, why should you use this:
Suppose my script is running, and there are a couple of things (I'm, for instance, looping through a nodes list) I might be needing later on. That's why I might choose to do something like this:
for(var i=0;i<nodesList.lenght;i++)
{
if (nodesList[i].id==="theOneINeed")
{
aClosure = (function(node,indexInNodesList)//assign here
{
return function()
{
node.style.display = 'none';//usable after the parent function returns
alert(indexInNodesList+ ' is now invisible');
}
})(nodesList[i],i);//pass the element and its index as arguments here
break;
}
}
i = 99999;
aClosure();//no arguments, but it'll still work, and say i was 15, even though I've just
//assigned another value to i, it'll alert '15 is now invisible'
What this enables me to do is to prevent function arguments from being garbage collected. Normally, after a function returns, all its var's and arguments are GC'd. But in this case, the function returned another function that has a link to those arguments (it needs them), so they're not GC'ed for as long as aClosure exists.
As I said in my comment. Google closures, practice a bit, and it'll dawn on you... they really are quite powerful

() right after a function means the function is going to get fired immediately? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What do empty parentheses () after a function declaration do in javascript?
I am looking at some Javascript code and trying to figure out what }(); right after return num+10 means. Does that mean the function will get executed immediately? Where can I get more information about this.
function addToTen(num) {
return function() {
return num+10;
}();
}
addToTen(5); // 15
Thanks,
Venn.
Yes, but only if it's a function expression, which is different from a function declaration. A function declaration is how your first function is defined:
function foo(){
}
If you add () after this, you get a Syntax Error. If the function is defined as a function expression, adding a set of parenthesis immediately executes it. Functions are expressions whenever they are not defined as above, e.g.:
(function(){}());
var x = function(){}();
return function(){}();
Your actual example is just... odd, and pointless. It's almost a classic closure example, something like:
function addTo(x){
return function(y){
return x + y;
}
}
var addToTen = addTo(10);
addToTen(5); // 15;
but your actual example is equivalent to just:
function addToTen(num){
return num + 10;
}
and all the extra stuff is completely unnecessary.
Yes, it means the function object is evaluated.
Just like with any other function, you have two ways of looking at it:
var myFunction = function(val) {
return val + 1;
}
To return the function object, or send it somewhere else, I just say myFunction
If I wish to execute it, I say myFunction()
In this closure or decorator, whatever, that you've described above, rather than return the function object itself, you're returning the value of executing that function immediately, hence the () afterwards.
Yes, it's executed immediately, but the usage doesn't make any sense in this example.
Often used for anonymous functions creating a closure.
see Why do you need to invoke an anonymous function on the same line?
One place where I use it a lot:
(function($) {
// secure way to ensure no conflict between $ (jQuery)
// and another js-framework can happen
$...
})(jQuery);

Categories

Resources