I'm new to JavaScript and making good progress. When I got to this part I was a little confused. Mostly the part that says "getName(first, last)". I don't quite get its purpose and what it does in detail. It wasn't declared with a "var" nor is it within the function, or "=" to anything. Also, I'm not to clear on the use of the parameters of the function. I'd really appreciate any help. I'm new to SE too and I'm loving it. Thanks in advance
var first = prompt("May I have the First Name");
var last = prompt("May I have the Last Name");
getName(first, last);
function getName(var1, var2) {
var x = var1 + " " + var2;
alert("The name is " + x);
}
Jarad
getName is a function in your JavaScript code which have two parameter var1 & var2. This function simply concatinate these two parameters with your text "The name is " and show in an alert message.
And the line getName(first,last); is calling your function getName() & passing two arguments first & last. You can pass any two arguments to this function and it will show it in an alert.
e.g: instead of using first & last, you can use the below code and see the result.
var x = 'Mr';
var y = 'Ayaz';
getName(x,y);
getName(first, last); is a function call. You're providing the function with two pieces of data (first name and last name) and instructing it to execute. The data you're providing it are called arguments, the identifiers in the function declaration are called parameters. The names do not need to match. Inside the function, the names it uses are the parameter names.
When you call
getName(first, last);
Control jumps to that function and the body (the part inside {} is executed).
Function declarations create a variable, with the same name as the function, in the current scope and are hoisted.
Related
I'm wondering if this way of passing an argument from one function to another (let's say from f1 to f2):
f1 = function(arg){
f2(arg);
}
f2 = function(arg){
//doing sth with passed argument
}
Is wrong? Or is it better/safer to always use the .apply() method, even if we're not passing an array?
To clarify- argument is passed only to f1, and only from f1 f2 is called.
No, it's not wrong.
Passing parameters through functions is one of the fundamental aspects of JavaScript as a language. It helps you take a complex application and break it down into manageable chunks for both clarity and maintainability.
.apply is useful when you want to call a function with a specific scope ( that's why the first parameter is this ) and it takes an array or array-like secondary parameter for arguments to be used within the function. The fact that it's an array/array-like makes no difference at all to you as a programmer or to the function that you're calling. There's nothing special about it, it's just the format that apply expects.
Nothing wrong about that at all. This happens all the time.
The only reason you should use apply() is if you need what it does, like changing the context (value of this) or passing an array as individual arguments. You aren't doing anything like that here, so there is absolutely no reason to make more complicated.
When you declare an argument in JavaScript it's treated just like a variable, and you can use it like any other variable: reassign values, pass it to another function, etc. .apply(this, arguments) is also possible, but it's not necessary unless you need to set the this of the called function or to pass an arbitrary number of arguments.
The apply() method takes arguments as an array.
The apply() method is very handy if you want to use an array instead of an argument list.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>In this example the fullName method of person is <b>applied</b> on person1:</p>
<p id="demo"></p>
<script>
var person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
var person1 = {
firstName:"John",
lastName: "Doe",
}
var x = person.fullName.apply(person1, ["Oslo", "Norway"]);
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
While if you use two function and call One in another:
function function_one() { function_two(); }
function function_two() {
//enter code here
}
Function parameters are the names listed in the function definition.
Function arguments are the real values passed to (and received by) the function.
Parameter Rules
JavaScript function definitions do not specify data types for parameters.
JavaScript functions do not perform type checking on the passed arguments.
JavaScript functions do not check the number of arguments received.
Parameter Defaults
If a function is called with missing arguments(less than declared), the missing values are set to: undefined
more information JavaScript you can read this link
https://developer.mozilla.org/it/docs/Web/JavaScript
With javascript closures and callbacks, I am confused on the difference between why the parameters that a named, nested function take are different (inherited from the outer function?) than a closure's parameters. For example:
var filter = function (collection, test) {
var newArray = [];
each(collection, function (value) {
if (test(value)) {
newArray.push(value);
}
});
return newArray;
};
The filter function operates on the each function. What input does the "value" parameter (in each) correspond to? Does a callback function's parameter automatically line up with filter's first parameter because they are both the first parameter of their respective functions? If the outer function and the inner one both accepted another parameter, would those line up because of their position as well? The parameter relationship between the inner/outer function here seems to be different from a closure's parameter (the closure seems to accept a new parameter; its parameters don't line up with the outer one's parameters) For example:
var outer = function(par1, par2) {
var hold = par1 + par2;
function inner(par3) {
return par3 + par1 + par2;
}
return inner;
};
var closure = outer (5,4);
closure(2);
I see that the inner function is returned from the outer function (when stored in another variable) and takes its own parameter separate from the outer function.
Do named/established functions inherit their parameter correspondence from their enclosing functions?
Do callback functions take on their own parameter - separate from their enclosing function - because they are returned out of that function and saved to a variable?
What input does the "value" parameter (in each) correspond to?
That depends on what each does. It isn't a standard JS global and you haven't shared your definition of it.
Does a callback function's parameter automatically line up with filter's first parameter because they are both the first parameter of their respective functions?
No. The arguments pass to any function are dependant on the code that calls that function.
If the outer function and the inner one both accepted another parameter, would those line up because of their position as well?
No.
Do named/established functions inherit their parameter correspondence from their enclosing functions?
No.
Do callback functions take on their own parameter - separate from their enclosing function
Yes
because they are returned out of that function and saved to a variable?
No. It is because they are functions.
function outer(foo, bar) {
console.log("Outer gets foo " + foo + " because foo is a argument of outer");
console.log("Outer gets bar " + bar + " because foo is a argument of outer");
return inner;
function inner(baz) {
console.log("Inner gets foo " + foo + " because foo is a variable still in scope");
console.log("Inner gets bar " + bar + " because bar is a variable still in scope");
console.log("Inner gets baz " + baz + " because baz is an argument of inner");
}
}
var returned_inner = outer(1, 2);
returned_inner(3);
With javascript closures and callbacks, I am confused on the difference between why the parameters that a named, nested function take are different (inherited from the outer function?) than a closure's parameters.
Your confusion problem springs from the simple fact that, most of the time, when you are using a callback, the function that actually calls it is written by someone else and you never look at it.
I think I can sum up the answer to all of the questions by saying that there is absolutely no requirement at all for the parameters of an inner function to have anything at all to do with the parameters of the enclosing function.
They are completely unrelated values.
For example:
function f(a, b, c, d, e) {
// You mentioned "named, nested" function in your question...
return function unusedName(x) {return x}
}
console.log(f(1, 2, 3, "four", 25/5)(100));
will display 100.
Of course, in reality, you would want the inner function to somehow or other use the parameters of the outer function, otherwise the parameters to the outer function are useless.
But there is no requirement that they "line up." How you create your closure, that is how your returned inner function decides to use the values from the environment provided by the outer function, is wholly up to you. The language itself enforces nothing.
Please consider changing most of the hypotheses in the question :-)
Identifier scope.
When javascript code uses an unadorned identifier (such as a variable name, the name of an object or the name of a function) inside a function, the javascript engine looks to see if the identifier is the name of a local variable, the name of a nested function defined within the same function body, or the name of a formal parameter. If not found it will search for the identifier, in the same manner, in a next most outer function (if a function searched is nested), or look for the identifier in global scope if the last function searched was itself global.
Hence there is no "lining up" of nested function parameters, there is just searching the scope chain. Outer function parameters, variables and named function definitions are all in scope of inner functions. There is no automatic "relationship" between formal parameter definitions in different functions unless planned by the programmer.
Closures
Be careful about categorizing functions as call backs or closures. Often a call back function forms a closure. In summary, a closure is caused by keeping a reference to a nested function after its outer function has returned. This can result from storing a reference to the inner function either before or after the outer function returns, or by passing a reference to the inner function to some other function for use as an asynchronous call back. A long as reference to the inner function is being held somewhere, any values it references within its scope chain cannot be made available for garbage collection because they are accessible.
forEach
The each function appears to be an iterator function being applied to the collection passed as an argument. Javascript supports a standardized forEach to iterated over Array, Map and Set objects. Please refer to documentation for further details on how it is called and calls back call back function.
How does these code work ?
function output(a) {
console.log( "The function filter return " + a + "!");
}
x = function(data, fun) {
a = data;
fun(a);
};
theInput = " TEXT FROM INPUT ";
x(theInput, output);//The function filter return TEXT FROM INPUT !
I wrote it by mysels , and it works fine . But I don't understand how 'function1(data, function2)' run .
What is x?
It is a variable that holds a reference to a function with two parameters, data and fun.
Whats are you doing here?
x(theInput, output);
You call this function passing a string and a function. Yes, functions in JavaScript can be treated as any other object. Actually, they are also objects. So they can be stored to variables (store a reference to them), they can be passed as arguments to another function etc.
What is happening inside the body of the function that is stored in x ?
Initially, you assign the data to the variable called a and then you pass this as an argument to the function output. Then the function that is stored in output is called.
If there is one takeaway from this code snippet is the fact that you passed a function as an argument to another function. This is very important in JavaScript and it is associated with the nature of functions in JavaScript.
According to MDN:
In JavaScript, functions are first-class objects, i.e. they are
objects and can be manipulated and passed around just like any other
object. Specifically, they are Function objects.
Firstly I came to know the difference between apply() and call().
function theFunction(name, profession) {
alert("My name is " + name + " and I am a " + profession + ".");
}
theFunction("John", "fireman");
theFunction.apply(undefined, ["Susan", "school teacher"]); // This call be called theFunction("Susan", "school teacher");, why use apply
theFunction.call(undefined, "Claude", "mathematician"); // This call be called theFunction("Claude", "mathematician");, why use call
From the above code, all the 3 function call displays the alert message.
What are the advantages/disadvantages of using apply and call, over normal function call, and when is it appropriate to use apply/call, please clarify me.
One more thing, what if the function is a prototype based function:
Function.prototype.theFunction = function(name, profession) {
alert("My name is " + name + " and I am a " + profession + ".");
}
Then how to call this function bu using apply or call. I tried this way:
theFunction.apply(undefined, ["Susan", "school teacher"]);
theFunction.call(undefined, "Claude", "mathematician");
but resulted in error.
"ReferenceError: theFunction is not defined"
As you have said it seems that you already know what these to functions apply() and call() actually do, but in terms of their uses, I'd say they are used mostly when you want to provide your function with a specific object of your own, as its this value in its context.
One of the most popular use of these two is to handle array-like objects like arguments objects in the function:
function(){
//let's say you want to remove the first parameter from the arguments object
//you can make sure that
console.log(arguments instanceof Array);//false
//as you see arguments is not an actual array object but it is something similar
//and you want slice out its value
var myparams = Array.prototype.slice.call(arguments, 1);
//here you have myparams without your first argument
console.log(arguments);
}
Let's go with another example. Say we have an independent function like:
function getName(){
console.log(this.name);
}
Now you can use it for any kind of JavaScript object that has a name attribute:
var myInfo = {
name: 'SAM'
};
now if you do:
getName.call(myInfo);
what it does is printing out the name attribute or you can try it on the function itself:
getName.call(getName);
which would print out the function's name ("getName") in the console.
But similar to my first example, it is usually used when you want to use functions that are not in the object's prototype chain. The other example of that could be:
//let's say you have an array
var myArray = [1 , 2];
//now if you use its toString function
console.log(myArray.toString());//output: "1,2"
//But you can use the Object toString funcion
//which is mostly useful for type checking
console.log(Object.prototype.toString.call(myArray));//output: "[object Array]"
This post gives a very detailed explanation of call() and apply().
TLDR;
Both call() and apply() are methods we can use to assign the this
pointer for the duration of a method invocation
The apply() method is identical to call(), except apply() requires an
array as the second parameter. The array represents the arguments for
the target method.
The main difference is that apply lets you invoke the function with arguments as an array; call requires the parameters be listed explicitly.
It Will Give You More Explaination
POST
Yes I know eval is evil but ...
Few times I saw a function being created from a string in few different ways:
var s = "function fname() { this.m = function(s){alert(s);}}";
//1
var x = new( eval("("+s+")") );
x.m("aaa")
//2
var x = new( eval('[' + s + ']')[0] );
x.m("bbb")
//3
var x = new ( eval(s + " fname;") );
x.m("ccc")
The first 2 are clear to me but I wonder about the third one.
Could someone explain how adding a name of the function after it's definition helps eval do the job ?
Also do you know any other ways of using eval to create funcions ?
Thanks
Szymon
First, with the function declaration (which is not an expression), you create the function and put it into the current scope:
function fname() { ... }
The closing brace finishes the function statement, and an expression follows:
fname
As the function is already in the scope, the expression fname simply refers to the function. And because the expression is the last thing in your eval'ed code, eval returns exactly that function reference.
Instead of fname, you could write the name of any function in the current scope, e.g. alert, which would then be returned by eval.
function fname() { this.m = function(s){alert(s);}}
is a function declaration. Eval would create it, but not return it, so after it another statement is added that just evaluates to the function reference.
In the other two examples it will be a function expression (with brackets around, or inside array literal), which itself evaluates to the reference.