This is so simple I forgot how to do it. I've always passed variables to a function hence it's param's were pre-set, now I need to set the param's when declaring the function, but don't remember the setup.
I'm looking for the working version of this:
function(a,b=4){return a-b;}
Where the b param' of the function is set when the function is declared.
If I remember rightly it's like setting a default for b if the function has no second argument:
function(a,b){b=b || 4; return a-b;}
EDIT
Thanks for all your help but it seems it's impossible in js without ECMAScript 6. Your answers are getting a bit off topic though... I really needed the values set in the paren's.
To keep it on topic... my initial problem is sending parameters to a setTimeout function. Ok so I have a <div> with a .gif background, when clicked it's background changes, this second animation runs for exactly 8 seconds and then the background changes again to a final .gif. so it's a 3 stage animation, simple... thing is the 8sec gap, I figured a setTimeout would work but I can't pass any param's to the 'sto' function to reference said <div>.
If you know of any timer events that can help then be my guest, this is as far as I've got. My original code is below... it fails at function(p = cha).
for(var i = 0; i < 5; i++){
var cha = document.createElement('div');
$(cha).css('background','url(img/stand.gif)');
cha.addEventListener('click',function(){
$(cha).css('background','url(img/walk.gif)');
setTimeout(function(p = cha){
$(p).css('background','url(img/walk.gif)');
},8000);
});
}
function(a,b){b=b || 4; return a-b;}
This is the typical way to default params in ES5. However I would advise changing this to check b's typs a little more strictly, because 0 will be considered a falsey value by the || operator
function(a,b){
b = typeof b === 'undefined' ? 4 : b;
return a-b;
}
Related
I got this code from the Headfirst Javascript book. I changed the function names to be clearer. I'm trying to wrap my head around this.
I assigned add to the function outer with a number. That number remains for some reason - returns a reference to inner with n = num (which returns the added values?
Anytime I change outers n value, the inner will use that new value?
I believe I'm right on that. Is there anywhere I can read more about it? See better examples? Or can anyone explain this better?
function outer(n) {
var inner = function(x) { //or x = 0
return n + (x || 0); //added default 0 for testing to prevent NaN
}
return inner;
}
var num = 2;
var add = outer(num);
console.log(`Adding 2 to num(${num}): ${add(2)}`);
add = outer(5);
console.log(add());
console.log(add(2));
In JavaScript, functions can act as regular data. If you are OK with the idea of passing a number or string around, then passing a function around is no different. This allows you the ability to do some very cool and powerful things.
Here, instead of the add function simply giving you your numeric answer, it's giving you back a function with your number embedded into it. This means that add doesn't really add anything, add is a function for creating functions (similar to the idea of a "Factory" in class based programming).
Changing the names may make things easier:
function createAddFunction(numberThatWillBeHardWiredIntoReturnedFunction) {
var resultingFunction= function(x) { //or x = 0
return numberThatWillBeHardWiredIntoReturnedFunction + (x || 0);
}
return resultingFunction;
}
var num = 2;
// This will cause add to be a function that is hard-wired to add 2 to another number
var add = createAddFunction(num);
console.log(`Adding 2 to num(${num}): ${add(2)}`);
// This will cause add to be a function that is hard-wired to add 5 to another number
add = createAddFunction(5);
console.log(add());
console.log(add(2));
Let's rename the functions to make it even clearer. The outer function takes a parameter and uses it to create a new function. This new function is returned for future use.
function createFunctionThatAdds(n){
var adds_n = function(x) { return n + (x || 0); };
return adds_n;
}
var adds_2 = createFunctionThatAdds(2);
var adds_5 = createFunctionThatAdds(5);
console.log(adds_2(10));
console.log(adds_5(10));
The technique used is called currying. It's part of functional javascript.
You can read more about it here.
The idea behind it is that you can use a function to generate another function, which you can use further in your code.
Currying is made possible, because of a closure.
There are a lot of libraries that are built based on that principe, for example Ramda.
Please: only pure vanilla JS code. No jQuery or other external things, thank you. :)
How can I create a function that contains sub-functions but also returns a value if no sub-function is called?
For example, let's take a number variable num.
I want to add a round() function to the number variable; if it's called directly, I want it to round up or down depending on the variable's actual value.
var num=4.12;
num.prototype.round=function(){return Math.round(this);}
Now I wand round() to have sub-functions that will round up or down, disregarding the decimal values.
num.prototype.round.up=function(){return Math.ceil(this);}
num.prototype.round.down=function(){return Math.floor(this);}
If I do that and log num.round() to console, it does what it's supposed to. But if I log num.round.up() to console, I get an error telling me that num.round.up() is not a function.
So I try putting the sub-functions into the main function declaration like this:
num.prototype.round=function(){
var n=this;
this.up=function(){return Math.ceil(n);}
this.prototype.round.down=function(){return Math.floor(n);}
return Math.round(n);
}
Then again, num.round() will return the correctly rounded value, but both num.round.up() and num.round.down() will return "not a function" errors.
I'm going nuts trying to figure this out... I didn't only try what I mentioned above, but I also tried doing this with immediately executing functions like this:
num.round=(function(){
return function(){
var that=this;
/* anything in here is already useless because this
is no longer num's value but [Object window]... */
}
})();
I guess part of the trouble is that I'm so weak at OOP that I just have no clue about the correct terminology... naturally, that doesn't help when searching for clues or when it comes to knowing any potential reasons why something like this should not work...
So is there any way at all to do this?
Well you can pass a parameter to the function. Not the exact implementation you want, just an alternative:
var num = function (defaultNumValue) {
var delegation = {
'up': 'ceil',
'down': 'floor'
};
return {
round: function (val) {
return Math[ delegation[val] || 'round' ](defaultNumValue);
}
}
};
var sth = num(1.5);
sth.round(); // 2
sth.round('up'); // 2
sth.round('down'); // 1
May be something like:
function num(n) {
this.num=n;
this.round=Math.round(n);
this.up=Math.ceil(n);
this.down=Math.floor(n);
this.up2=function(){return Math.ceil(n);}
}
var num = new num(4.12);
alert(num.num);
alert(num.round);
alert(num.up);
alert(num.down);
alert(num.up2());
I am making a website for school and we where working with function. Now i got a litle "problem"
i am using jquery to change the DOM and made a function where you can choose which location you are adding the element to.
Something like this:
function functioname(parameter){
console.log(parameter);
}
when i call this function like this:
functioname("#id");
i will return "#id";
But if i call it like this:
functioname (id);
I get return with the whole div and his children. How can this happen?
And why works this only with divs.
It isn't really a problem i was just wondering how this works.
Thanks in advance if somebody could explain what is happening here.
The window.id will find a DOM element whose id it matches. For example, window.mydiv will find:
<div id="mydiv"></div>
However, this not a recommended practice.
As a general rule, relying on this will lead to brittle code. Which IDs end up mapping to this API can vary over time, as new features are added to the Web platform, for example. Instead of this, use document.getElementById() or document.querySelector().
http://www.w3.org/html/wg/drafts/html/master/browsers.html#named-access-on-the-window-object
In the first function you are passing the string and in the second example you are passing the window object. Same as we pass an object with "this"
<div onclick= " functionname(this); "> </div>
here we get the complete object inside the function.
In first line of code "#id" you are passing the string. it's return the string also as you says.
in second you pass object id that you have earlier in your code. This is maybe why you got the different result.
Let's take a look at the window object. The window is pretty cool in that it allows you to declare global variables from anywhere on the fly. Take the following code for example
//the following three lines of code do the same thing
//create a global variable and store a value in it
window.a = 1;
window["b"] = 2;
var c = 3; //this one is most used though
function g() {
//the following three lines of code do not do the same thing
window.d = 4; //global
window["e"] = 5; //global
var f = 6; //local
}
g();
console.log(a); //prints 1
console.log(b); //prints 2
console.log(c); //prints 3
console.log(d); //prints 4
console.log(e); //prints 5
try {
console.log(f); //ERROR
} catch (err) {
console.log(err);
}
console.log(window.a); //prints 1
console.log(window.b); //prints 2
console.log(window.c); //prints undefined
console.log(window.d); //prints 4
console.log(window.e); //prints 5
console.log(window.f); //prints undefined
console.log(window["a"]); //prints 1
console.log(window["b"]); //prints 2
console.log(window["c"]); //prints undefined
console.log(window["d"]); //prints 4
console.log(window["e"]); //prints 5
console.log(window["f"]); //prints undefined
It is important to know that obj.prop === obj["prop"] is always true in JavaScript. That is why the last two sets of tests have the same results. Also important is prop === window.prop unless you declared prop using var prop;. This is because JavaScript secretly uses the special keyword using on the window variable at all times unless otherwise specified.
All browsers make DOM elements available via id using document.getElementByID but some browsers are nice enough to set up some variables for you so you don't have to write all that code. Imagine that a browser runs this script before any of your scripts do
(function(context) {
var tags = document.getElementsByTagName("*");
for (var i = 0; i < tags.length; i++) {
var tag = tags[i];
if (tag.id) {
context[tag.id] = tag;
}
}
}(window));
Which fills the window variable / global scope with tags that have ids.
Here are a bunch of examples. http://jsfiddle.net/Lk345zez/
There is something wrong with my code, but I can't find what it is. The first time I call registerStartDateValidation, the value of the startDateValidation variable in the defineKeyword closure is of course the same than what was affected outside the closure. But the second time, the variable is reaffected with another value, but the value of startDateValidation in the defineKeyword is still equal to the value of the first time we call registerStartDateValidation. Does the closure cache the variable?
Tv4.prototype.registerStartDateValidation = function (attributes) {
var helper = this;
var dateNames = Object.keys(attributes);
var startDateName = dateNames[0];
var startDateString = attributes[startDateName];
var endDateName = dateNames[1];
var endDateString = attributes[endDateName];
var startDateValidation = helper.startDateValidation(startDateString, startDateName, endDateString, endDateName);
console.log(startDateValidation)//First time equal "true", second time equal "false"
tv4.defineKeyword('startDate', function (data, value) {
if (value === 'startDate') {
console.log(startDateValidation)//First time equal "true", second time still equal "true"
return startDateValidation
}
});
};
Note that there is nothing making an ajax request, that could mess up the order the functions are called.
Short answer: no, a closure won't cache the variable, so there is something else going on in your code. Reducing the problem to a simple complete example that demonstrates the problem will usually make it obvious where the problem is coming from, or at least help other people figure it out.
However, since it looks like you're referring to is this project, it may be possible to figure out what's going on. Tv4.defineKeyword() appends new functions to a list if it is called multiple times for the same keyword. Since you're calling tv4.defineKeyword (note the lower-case 't') and not helper.defineKeyword or this.defineKeyword, it looks like each call to registerStartDateValidation will affect the same instance, so you are almost certainly adding a validation function when you meant to replace it.
In this JavaScript lesson on Codecademy it is required to write a do/while loop, I have written this, and it passes
var getToDaChoppa = function(b){
var a = b;
do{
console.log("Dunno!");
} while (a < b);
};
getToDaChoppa(25);
But when looking closely at my code, I think that I may have done it completely wrong since a has no defined value?
Or since the variable of b is local inside the function, it does not affect the b argument which is passed a value of 25?
Many thanks in advance.
It simply does only one iteration, because when the do while loop starts, the condition is not satisfied because a and b are equals. So
var getToDaChoppa = function(b){
var a = b;
do{
console.log("Dunno!");
} while (a < b); //25 < 25, exit
};
getToDaChoppa(25);
If you want to try a do while loop try with some trick like
var getToDaChoppa = function(b){
var a = 10; //or whatever minor than b
do{
console.log("Dunno!");
a++; //when it reaches 25 or whatever value you set it breaks the loop
} while (a < b);
};
This is just an example to let you figure out how do while works
The code's fine, the logic's wrong. You are assigning a the value of b, so they'll be always equal.
You are assigning the value of b to a with the statement var a = b;
The loop will run once since you are using a do while loop.
The code is not wrong, it is designed to illustrate that the condition is evaluated after the first iteration of the loop.
http://jsfiddle.net/puleos/QXC9z/
Is this JavaScript code wrong?
depends on what problem you wanted to solve.
It looks pretty useless to me since the body of the loop will always be executed once.
while (a < b);will always return false because of var a = b; and a is not modified in the loop.
I think what you're after is:
var getToDaChoppa = function(b){
var a = 0;
do{
console.log("Dunno!");
a++;
} while (a < b);
};
As mentioned by other posters, if a = b the loop will only run once. This version should run the expected number of times (if that truly is what's expected).
Since the question says "Your loop should print a string of your choice to the editor one time", I think this is correct. Your code will print the string "Dunno!" exactly one time.
However the a and b variables and the do..while loop might as well not exist at all, they are only adding unnecessary complexity to the code which could be simplified to one line (the console.log() call).