+ 5
javascript question explication needed
the code: const add = a => b => a+b; const add3 = add(3); console.log(add(2)(5) === add3(4)); the output is : true Can anyone explain how this code function? what does => mean? Is add and add3 variables?
5 Respuestas
+ 9
This is an example of a function inside another function. => is for creating arrow functions.
There is a lesson in the Sololearn app about this also : https://www.sololearn.com/learn/409/?ref=app
it can be written in simpler form as :
const add= function(a){
return function(b){
return a+b;
}
}
then,
add3 becomes
function (b){
return 3+b;
}
so, add(2)(3) gives 2+5 which is 7 and add3(4) gives 3+4 which is 7
7==7 so, the output is true.
So, add is a function and add3 is also a function and, they are constants. Constants are like variables with let but their value cannot be changed.
Agent your answer is as wrong and misleading as possible.
=> is for arrow functions not greater than or equal to (that is >=).
add3 is a Function not 6. And your replace logic is also weird.
+ 6
oh sorry Swapnil Srivastava
I thaught this was a different language.
+ 6
Mr Jami , the variables add and add3 are constants. This means that their value cannot be changed.
Eg. you try :
const a=5;
a=7; //In sloppy mode this will be ignored. In strict mode, this will be an error.
console.log(a);// It will be 5 because a is read only.
Just think that just like Strings and Numbers, Functions are also a variable type. Calling them does not change their value.
+ 4
=> is new Js syntax to declare or define function.
Eg. :
function a(a) can also be written as
const a => a.
Line one (old syntax) :
var add = function (a){
return function (b)
{
return a+b
}
Line 2:
You are passing 3 to a and storing it in add3 variable.
Line 3:
Here you are passing 4 to inner function argument b and comparing it with add function having argument 2 for a and 5 for b(2+5 = 3+4 hence true).
Ok ok I know its pretty big explanation but hope this helps😊😊.
+ 3
"So, add is a function and add3 is also a function and, they are constants"
how they are constants when they output different values with different parameters?
Swapnil Srivastava