Firstly, I'm a beginner, so don't be mad if what I'm saying is stupid.
So, this is the code that is using parameters:
function simpleExample (x) {
document.write ("I love " + x);
}
simpleExample ("my mom.");
And this is the code that doesn't use the parameters:
function simpleExample () {
var x = ("my mom");// Does not use the parameters
document.write ("I love " + x);
}
simpleExample ();
So, the result is the same and... the global and local thing is also the same [both is local right?] So what does the difference?
Sorry if it's a dumb question.
You maybe right if you just want to say you're loving your mom. But, what if you also want to say other persons that you love? You write all that hard code everytime?
the answer is : no.
You just call that function with a parameter. And that's it. Nothing more.
simpleExample("my mom");
simpleExample("my dad");
simpleExample("justin bieber"); //we all hope you don't.
Why use the parameters if we can use variables?
The point is that often we cannot use static (global) or constant variables. Consider your first function:
simpleExample("my mom.");
simpleExample("my dad.");
We are calling the same function multiple times with different arguments. This requires parametrisation of the code in the function that is otherwise the same for all cases.
Using a parameter for a function allows the result of the function (be it a process or a result value) to differ based on an input that is not fixed at the time of writing the function.
Even with your simple example it should be obvious that the simpleExample(x) function with a parameter can be easily reused like so:
simpleExample('my mom');
simpleExample('and my dad too!');
simpleExample('my sister not so much');
This wouldn't be as easy with the variable approach.
Using parameters is the essence of functions.
In the second case, the variable x is local to the scope of the fonction and will never change. That is, the execution of your function simpleExample will always have the same effect (logging "I love my mom" in the console).
The use of parameters allows your function to have an effect dependent to the input. In this case, the person you love can be changed depending of the parameter x.
Related
So I have a good grasp of most static typed languages mainly C and C++. But when I went into javascript I noticed something that bummed me out.
I learned to write this function to interact with inner HTML:
document.getElementById("SomeHTML").onclick = function(){
document.getElementById("AnotherHTML").innerHTML = "<p> Joe has a cat </p>";
}
That is all fine and well but there is a problem. How am I supposed to reuse this and keep it readable?... coming from a C++, I was always taught to write code in this way:
function MyFunc()
{
document.getElementById("AnotherHTML").innerHTML = "<p> Joe has a cat </p>";
}
document.getElementById("SomeHTML").onclick = MyFunc();
The latter code being cleaner (at least to me) and I can reuse the function, but it doesn't work ... I am able to write this way in every programming language yet in javascript it produces an error. I don't know what I am missing, I know its something simple. Can someone please help me understand why I cant write javascript functions in this way? Or if I can please tell me how, because I much prefer the latter than the former. thanx in advance.
You're in luck! The latter code will work in JavaScript as well.
Below, I've outlined three different ways you can achieve this using a more familiar syntax.
// The function to call
function MyFunc(){
alert('Working!');
}
// Option 1 (Link 1)
document.getElementById("one").addEventListener("click", MyFunc);
// Option 2 (Link 2)
document.getElementById("two").onclick = MyFunc;
Link 1<br>
Link 2<br>
Link 3
Your function is not quite reusable, to me I would have used another approach
// Original version
function MyFunc() {
document.getElementById("AnotherHTML").innerHTML = "<p> Joe has a cat </p>";
}
document.getElementById("SomeHTML").onclick = MyFunc();
// Function Generator
function MyFunc_generator(element, html_content) {
return function() {
element.innerHTML = html_content;
}
}
myfunc = MyFunc_generator(
document.getElementById("AnotherHTML"),
"<p> Joe has a cat </p>"
}
document.getElementById("SomeHTML").addEventListener("click", myfunc);
There are quite some difference in the code.
We can start with comparing the original MyFunc function and the MyFunc_generator one.
The first does not have a return statement and so the assignment
document.getElementById("SomeHTML").onclick = MyFunc(); would assign the value undefined the the onclik handler of the html element whose id is "SomeHTML".
The "MyFunc_generator" function is an Higher order function, a function that return a function as result of his evaluation.
The execution of the generator function has the result to create a specialized function with real values instead that generic ones.
The assignment in the example would create a function (anonymous) and assign the name myfunc to it. That function will be equal to your.
You can change the parameters of the generator to create similar function with different targets, and/or different content.
Obviously the effort in a such simple case will not worth the result but if the strategy you have to describe is quite complex the benefit will increase.
One last note. The assignment of the handler function to the event is different. In javascript the preferred way is with addEventListener
I imagine this comes up a lot. Let's say I have:
downloadData () {
var myData = //do something ;
displayData(myData);
}
displayData (myData) { //<--- is it bad practice to use same variable name myData?
//display data
}
Is it good or bad practice (or doesn't really matter) to use the same variable name in the second function displayData() or should I accept myData with some other name, like myDataToDisplay? Both names tell me what's in the var just as effectively.
As long as you declare the variables outside of the function properly (i.e. use "var") you shouldn't have any problems and it helps with making the code easier to read.
The variable myData is bounded to the scope of function displayData when displayData is invoked. So it's not like you're risking the possibility of any name collisions.
My general rule of thumb for parameter naming is clarity. So yes, I think it's perfectly fine to use the same name variable names in this case, insofar as they accurately describe the data that is being passed.
As a though experiment, lets suppose we had a hard rule that says "Thou shall not use the same variable names in multiple functions". What if you have multiple functions that call the same data and you're chaining the calls? That won't look pretty.
Its perfectly allright in this case because you are working with two different functions and scope of those variables are different. Though it depends on preference of coder but my suggestion is don't pollute your script by using same name again and again.
This is probably a stupidly basic question for this community, but if someone could explain it to me I would be very great full, I am so confused by it. I found this tutorial on the net and this was example.
<script type="text/javascript">
function sports (x){
alert("I love " + x);
}
sports ("Football");
sports ("Rally");
sports ("Rugby");
</script>
Why does this display the 3 variables: Football, Rally and Rugby?
Is it because x = sports? So when the variables of sports are defined they get displayed?
I think I confused myself more when writing this so I hope it kind of makes sense :(
Unless I'm missing something, the reason it shows all three variables (sequentially, not simultaneously) is because you're calling the function three times, each time you call it you're passing a variable ("Football" for example), which the function uses internally to complete the alerted message.
You're defining a function, called "sports", that takes one argument, named "x". Each time you call the function, it alerts a message, substituting the argument you pass in for "x". In this example, you call the function three times, with three different values of "x".
I hope this helps you, x is a container for a value. So when you say something like sports ("Football"); it behaves as if this:
alert("I love " + x);
was actually this:
alert("I love " + "Football");
This is because x contains "Football".
Think of it as a placeholder for a value of some kind.
Every time you write sports("text") you call a function. It means that it is executed.
Your function is displaying an alert message using an argument. In your case you execute your function three times with 3 different arguments.
Im a newbie programmer who got the function below from Stoyan Stefanovs object oriented JavaScript Book. He says that if you call next three times, it will output "a" and "b" and then "c". When I tried it in firebug console, it kept giving me "a", so that`s one question (a) i.e. is there something about firebug that would explain my result?
Next, I tried to run it in jsfiddle.net but it won`t output anything. http://jsfiddle.net/mjmitche/SkSMm/
Im sure Im doing something wrong, but what? Please explain if you can. Note, I did next(); and got A, and then I did next(); again and got 'a' and next(); again and got 'a'. In other words, the counter didnt change or didnt remember.
function setup(x) {
var i = 0;
return function () {
return x[i++];
};
}
var next = setup(['a','b','c']);
next();
Here is the jsfiddle link to show it works:
http://jsfiddle.net/ZnZTk/
JsFiddle is not like the console, it doesn't have a window where it will output return values. The result of the code is a web page, that is shown at the lower right.
You can use the alert method to show the values:
alert(next());
http://jsfiddle.net/SkSMm/4/
As you see, calling next three times will actually output the three values in the array. The setup function returns a delegate to the anonumous function that is created in the function. As that anonymous function uses variables outside itself, but which are local to the surrounding function, a closure is created for the function. The closure will contain the i and x variables. As the closure belongs to the delegate, it will survive from one function call to the next, and retain the values of it's variables.
You could do a similar thing just using global variables:
var x = ['a','b','c'];
var i = 0;
function next() {
return x[i++];
}
alert(next());
alert(next());
alert(next());
As the variables are declared outside the function, they will survive between the function calls.
The drawback of using global variables is that one script easily clashes with another if the variables are not given very unique names. If you use a closure, there is no risk of the variables of one script to conflict with variables of another script.
You did it wrong:
And jsfiddle: http://jsfiddle.net/ZHgW2/
Here's a neat demo that takes advantage of an imported say function and relies on a button:
http://jsfiddle.net/entropo/wxTqR/
This is a great way to test your scripts without relying on the log or alerts.
The say function is from jQuery in Action. Excerpt:
Within this function, we employ the services of a small utility function, say() C,
that we use to emit text messages to a dynamically created element on the page
that we’ll call the “console.” This function is declared within the imported support
script file (jqia2.support.js), and will save us the trouble of using annoying and disruptive alerts to indicate when things happen on our page. We’ll be using this handy function in many of the examples throughout the remainder of the book.
A few days ago, I asked a question regarding dynamically modifying a function's code midway through the outerlying script's execution and I was told to completely forget ever coming upon the notion. I'm not sure I understand why that is. Let me give an example:
<script>
var display = function(msg)
{
alert(msg);
}
// Now, at the moment, the display() function
// is receiving a single parameter and alerting
// it to the user. I'm now going to use eval()
// to modify the display() function.
eval('display = ' + display.toString().replace('alert(', 'document.write('));
// Now, the display() function writes its parameter
// to the document as opposed to alerting it.
</script>
I realize this is a rather trivial example, but there must surely be some use that can be derived from being able to dynamically modify a function, something so useful by itself.
Although this may do what you need it to do, 6 months from now you (or the person maintaining your code) will be going "WTF?!"
If your use case is to alert or write based on some condition, why don't you write two different functions? Or have your function take another parameter that decides the output mode. Or pass in a function as a parameter that performs the actual output. Something, you know, a little more on the sane side. ;-)
There are cases where it could be useful to change a function's behavior, but there are better ways to do it. In your example, you could create new instances of the function that handle the output differently, by passing a function as an argument (similar to the strategy pattern):
function makeDisplay(displayStrategy) {
return function(msg) {
// I'm assuming you would do some additional processing here...
displayStrategy(msg);
}
}
var display = makeDisplay(alert);
// now modify display to use document.write
display = makeDisplay(function(msg) { document.write(msg); });
Well, using eval might be a security concern but modifying a function in real-time is ok. How else you can make memoization anyway?
Although, come to think of it, changing method signature isn't a great idea, other people won't know how to call this function after this, since it would depend on execution order and it's not easy to track usually.
I have found myself needing to do this in situations where I don't have the source code for a particular piece of vendor javascript; so that could be a legitimate use case. I agree that if you have another option, it's better to do it in a more organised way, editing the original function to be more flexible.