I'm reading someone's javascript code and I have a hard time understanding what they are trying to do here.
var add3 = add(3);
var add4 = add(4);
console.log(add3(4));
Can someone explain what is going on inside the console.log() here?
Is console.log just taking the add3 value and automatically adds it to a integer 4?
Thanks
window.console is how your browser gives feedback on the document it has downloaded and parsed. You can usually see it by pressing F12 and then clicking the "console" tab. It's a good substitute for alert, but you can also write JavaScript directly into it and then click "Run" (or press enter if it's a one-line command box). That's much easier than writing it to a file, saving it, refreshing, and seeing what happens.
Not knowing anything about your add function, it looks like it's meant to show an example of currying. So instead of saying:
function add(x, y){
return x + y;
}
You write:
function add(x){
return function(y){
return x + y;
}
}
Then you can do:
var add3 = add(3); //returns a function that will add 3 to anything
console.log(add3(4)); //returns 7.
console.log(add(3)(4)); //also returns 7.
This seems like a silly way to do it, but it's a way to generate functions on the fly. If I did add(3) to the first example, it would break and say "y is undefined" in the console. Using the curried example, var add3 = add(3) is like saying "well, I don't know what I want to add three to yet, so add3 will just be another function that will add 3 to anything."
console.log outputs its argument to the console.
Its arument (add3(4)) is a function call, that calls the function add3 with the argument 4.
add3 is a function that is generated by add.
The function add looks lke this (probably):
function add(n) {
return function(x) {
return n + x;
}
}
Related
I have a block of code that uses Math.random(). I noticed that occasionally the return value would be "Undefined". This is the code I used:
return data.map(val => {
var r = Math.random();
if (r < this.mutChance) {
console.log(Math.random);
debugger;
return this.rDna(val);
}
return val;
});
When i set the mutChance variable to 0 and let the code run for a bit eventually debugger gets called and shows the value of r to be undefined. I tried to reproduce the problem by running in console
var test = Math.random();
while(test){
test = Math.random();
}
However, this loop never ended. I have no idea why the function would act differently within my object, and the console.log(Math.random); Says that the function still has its native code. Nowhere do I override the random function, nor do I use the variable r anywhere else.
I am relatively new to JavaScript and couldn't find this problem anywhere else. The only other code I have imported is the p5.min.js package.
Problem was with how chrome was interpreting the very small values
Without console.log chrome shows it like this
With console.log chrome displays correctly
The return statement below doesn't output anything or errors, any reason why?
I tried Chrome and Firefox and repl.it.
Here is the code I have:
//Create a function that uses a return statement
function multiply(num1, num2){
return num1 * num2;
}
//Call the function
multiply(10,20 );
I don't get any output or errors.
if you return something, it means it returns something. Right now, you only call multiply(), this function returns a value but you assign it to nothing.
If you use the following:
var returnValue = multiply(5, 10)
your returnValue variable contains the return value of the multiply function.
You don't get any output because you haven't done anything to generate output. You aren't getting any errors because there are no errors in your code. (It's okay to not use the return value of the function; in fact, it's quite common.)
Just returning a value from a function doesn't output it anywhere, it just returns it from the function so you can use it in the code that called the function. One thing you might do with it is output it, but you also might just use it for something else, like including it in a calculation:
function multiply(num1, num2){
return num1 * num2;
}
// Using the return value to output it:
console.log(multiply(2, 3));
// Using it in another calcuation...
const x = multiply(2, 3) + 4;
// ...the result of which we might output if we like:
console.log(x);
But again, you might never output the result of a function. For instance, this code uses the result of the function document.getElementById to set up an event handler. Doing that has no output at all:
let clickCounter = 0;
document.getElementById("btn").addEventListener("click", function() {
++clickCounter;
});
<input type="button" value="Click Me" id="btn">
Unless you're not showing us all of your code, it's because you are not returning the value to anything. Functions that return a value need to have that value used somehow in order for it to be visible. Some examples might be:
Using it as a parameter in another method call (e.g., logging it to the console):
console.log(multiply(10,20));
Setting it to a variable:
var result = multiply(10,20);
Using it as a value in another piece of logic:
document.getElementById("equation").textContent = "10 x 20 = " + multiply(10,20);
Without actively capturing and/or using the return value of a method, it will not be displayed anywhere.
I have been dealing with issues in multiple pieces of code but it seems to boil down to what I’m showing in this demo. I think it is related to the ’s dereferencing of a closure:
function get_5(callback) {
var result = 5;
callback(result);
}
function get_self(x) {
return x;
}
get_5(console.log);
// 5
console.log(get_self(5));
// 5
In the first result, the first function ran as expected, sending its hidden variable into the input of the console.log function.
The second result also makes sense, as it really just proves the second function works: it takes what was fed in and returns it.
But things get strange when I try to combine the two functions:
var a = get_5(get_self);
console.log(a);
// Undefined!
This third result is undefined, strangely enough, and I am not sure why. Is the closure being dereferenced, maybe to the “sneakiness” of the get_self function? How can I fix this? As a bonus, is there a way to eliminate the get_self function entirely and be able to directly read the variable result, which isn’t modified, without specifying any particular callback?
get_5 has no return statement. It doesn't matter what you pass to get_5, it will always return undefined.
Perl will return the result of evaluating the last statement in a sub, but JavaScript will not.
If you want get_5 to return the result of calling the callback you pass to it, then you have to say so explicitly:
function get_5(callback) {
var result = 5;
return callback(result);
}
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());
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;
}