This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}
What is the difference between a function expression vs declaration in Javascript?
I am attempting to understand the "best practices" of javascript.
This code is from jqfundementals.com
// create a function that will greet a person,
// and assign the function to the `greet` variable
var greet = function( person, message ) {
var greeting = 'Hello, ' + person + '!';
log( greeting + ' ' + message );
};
greet( 'Jory', 'Welcome to JavaScript' );
greet( 'Rebecca', 'Thanks for joining us' );
Why should I assign the function to the greet variable?
My first impulse would be to write it like this:
function greet ( person, message ) {
var greeting = 'Hello, ' + person + '!';
log( greeting + ' ' + message );
};
What are the differences between these two implementations?
There aren't any differences between those snippets, except hoisting which allows you to call the former function in the lines before the definition. But this is just a simplistic example to get you warmed up. In reality, people don't assign these functions to variables but pass them directly to other functions. Or they otherwise use them in expression contexts. Or they dynamically decide which function to to store. Or anything else really.
There is no real difference but the var form enables you to declare-before-use incase you have recursive functions.
Simple example:
var func1, func2;
func1 = function (count) {
count = count - 2;
if (count > 0) {
func2(count);
}
}
func2 = function (count) {
func1(count + 1);
}
func1(10);
Although
function func1 (count) {
count = count - 2;
if (count > 0) {
func2(count);
}
}
function func2 (count) {
func1(count + 1);
}
func1(10);
is perfectly acceptable too. The interpreter will replace it with the former because of variable hoisting.
Related
I am trying to write a function in JavaScript where there will be an infinite call to greet(). The expected outcome is to have the greetings concatenated with each call.
console.log(greet('hello').greet('world').greet())
the output of the above should give Hello world
and there might be infinite greet('string')
My initial implementation looked like this:
let greet = function (a) {
return function (a) {
return function (c){
return c ? (b + " " + c ) : (a + " " + b);
}
}
};
However, the output is not as expected. I am facing some issues in the implementation and would like some help in resolving them. Can someone help me fix this issue? Thank you in advance."
Basically, have a function that returns an object with a function inside which in turn invokes the global function that returns an object... etc
let greet = a => ({
greet: b => b ? greet(a + ' ' + b) : a
})
console.log(greet('hello').greet('world').greet())
You are probably looking for fluent chaining in JavaScript. You can achieve this approach by creating your own custom class and keep returning this:
class Greeter {
content = '';
greet(string) {
this.content += (this.content.length ? ' ' : '') + string;
return this;
}
toString() {
return this.content;
}
}
const greeter = new Greeter();
const output = greeter
.greet('I')
.greet('can')
.greet('do')
.greet('this')
.greet('forever')
.toString();
console.log(output);
You can check other possibilities by searching it. For example on Stackoverflow are similliar questions.
The issue in your code is that you are using the variable b inside the innermost function, but it's not defined in the scope of that function. Also, you are declaring a function with the same name a in the inner function, which shadows the outer a parameter.
Here's a corrected version of the code:
let greet = function (a) {
let b = a;
return function (c) {
if (c) {
b = b + " " + c;
}
return {
greet: function (d) {
return greet(b + (d ? " " + d : ""));
}
};
};
};
With this code, you can call greet multiple times and concatenate the greetings with each call. For example:
console.log(greet('hello').greet('world').greet());
// Output: "Hello world"
Thank you all for responding to my issue.
i also came up through some implementation with traditional function expressions
here is my solution
let greet = function (a) {
return {
greet: function (b) {
return b ? greet(a + " " + b) : a;
}
}
};
This question already has answers here:
What is the purpose of a self executing function in javascript?
(21 answers)
Closed 7 years ago.
I am new to javascript and I might have dove into the deep end first. I have came across the following definition while reading design patterns in js. I don't understand the syntax used here, why is the "log" function definition in "()",
var log = (function() {
var log = "";
return {
add: function(msg) { log += msg + "\n"; },
show: function() { alert(log); log = ""; }
}
})();
Please point me in the right direction.
Without the parenthesis, the right hand side of your assignment is a function expression, and log is assigned a reference to that (anonymous) function expression, allowing to call log() later.
If you include the parenthesis, the wrapped function turns into a self-invoking function expression (and is immediately executed), so log is assigned whatever this function call returns.
As someone else already stated, your code shows an example of the so-called module pattern. Read much more about it here.
I don't understand the syntax used here, why is the "log" function
definition in "()"
Its basically self executing anonymous function. There are several ways of writing such functions.
(function() {
alert('hi there');
})();
! function() {
alert('hello');
}();
+ function() {
alert('plus');
}();
- function() {
alert('minus');
}();
Now such function can also return values:
var msg = (function() {
return 'hello';
})();
alert(msg);
var calc = (function() {
return {
add: function(a, b) {
return a + b;
},
sub: function(a, b) {
return a - b;
}
};
})();
alert(calc.add(4, 5));
I am not seeing the issue here. I am new at JavaScript. I have researched variable scope and this looks correct to me. The issue is the variable, useAge, in the legalAge function is undefined. I have it declared before the function and passing it as a parameter to the function.
"use strict";
function person(){
alert("person function 1");
var personName = prompt("Enter a name:", "enter name here");
var personAge = parseInt(prompt("Enter " + personName + "'s current age:", "enter age here"));
var votingStatus = legalAge();
var statusMessage = (votingStatus == true) ? "old enough" : "not old enough";
document.writeln("<b>" + personName + " is " + personAge + " years old " + statusMessage + "</b><br />");
return personAge;
}
var useAge = person();
alert("useAge: " + useAge);
alert("outside function");
function legalAge(useAge) {
alert("legalVoting function 2");
var canVote = (useAge >= 18) ? true : false;
alert("Can Vote: " + canVote);
alert("age: " + useAge);
return canVote;
}
person();
The problem is that you haven't passed personAge into the legalAge() function. You need:
var votingStatus = legalAge(personAge);
Otherwise useAge in legalAge() is undefined and you'll get errors using it.
Couple things to note here:
var useAge = person()
The above line will assign the return value from person() to useAge sure enough...
function legalAge(useAge) {
....
}
The above function has a parameter called useAge which is local to the function, and must be passed as an argument when calling the function. I.E. legalAge(10). This would be fine and dandy, except...
function person() {
....
var votingStatus = legalAge();
....
}
the person() function is defined to call legalAge() with no parameters. In doing so, legalAge executes and does not have a value for its parameter.
Also, the useAge parameter is different from the global useAge variable.
Hope this helps!
I would really like to do this:
var Html = function() {
alert('internal: ' + this.val);
};
Html.val = "x";
alert('external: ' + Html.val);
Html();
but it doesn't work. why? how can I get the function code to see values set after its creation?
- update -
because my original post was not so clear in its intent, and because I've posted a solution that's closer to the intention than that of other posters here, allow me to say that what I wanted was a mechanism for accessing the internal members of a function with the explicit purpose of being able to create a generic function that can be seeded to modify its behaviour later and independently
The this context of a JavaScript function depends on how you call the function. You can pass the context explicitly with call:
var Html = function() {
alert('internal: ' + this.val);
};
Html.call({ val:'x' });
If you meant to use the function as a constructor you can instantiate with new:
function Html(val) {
this.val = val;
}
var html = new Html('x'); // Must be used with `new`
alert('internal: '+ html.val);
You can add methods to the prototype if you want to extend your object:
Html.prototype.getVal = function() {
return 'internal: '+ this.val;
};
var html = new Html('x');
alert(html.getVal());
In Javascript, the "this" is the object associated to a method, not the method itself. The simplest solution would be to change the Html function to a method:
var html = {
val: "x",
draw: function(){
console.log('internal: ' + this.val);
}
}
html.draw();
html.val = "y"
html.draw();
If you want to keep the html function as a direct function you can either craete a wrapper around a method.
var Htmldraw = function(){
return html.draw();
}
html.val = "asd"
Or you can change the function to use lexically scoped variables instead of "this"
var val;
var Html = function() {
console.log('internal: ' + val);
};
val = "x";
alert('external: ' + val);
Html();
thank you both for taking the time to post elaborate answers. you both got thank you points.
I'm going to answer my own question for the sake of some poor sod who may struggle with this in the future... what I wanted to do is best accomplished as shown below (please see my edits in the original posting to clarify what my intention was):
function fn() {
this.val = "x";
this.show = function() {
alert("internal = " + this.val);
};
return this;
};
var x = fn();
alert("initial = " + x.val);
x.val = "y";
alert("reset = " + x.val);
x.show();
from which you can see that a variable internal to my function is accessible from the outside. This allows me to manufacture a function and subsequently load it with a bunch of data for its use, without having to pass parameters during its creation (which is useful because when the function is actually called (as opposed to created), it will receive a different set of parameters)
This question already has answers here:
Javascript functions like "var foo = function bar() ..."?
(9 answers)
Closed 9 years ago.
var add = function addnums(a,b)
{
return a+b;
}
alert("sum is " + addnums(10,20));
why can't i use addnums directly in the above Javascript ?
PS : I know other alternatives, the question is why the above specified method doesn't work.
You can.
var add = function addnums(a,b)
{
return a+b;
}
alert("sum is " + (function(a,b) { return a+b; })(10,20) );
Plus you may shorten the syntax:
var addnums = function(a,b) { ... }
or
function addnums(a,b) { ... }
You have an error writing the function write like the following:
var addnums = function(a,b)
{
return a+b;
}
alert("sum is " + addnums(10,20));
:)
var add; is a declaration. Here add is declared and assigned a function you need not name the function after keyword function, variable name will take the function name when you define a function in this way. I think you understand now.