javascript question explication needed | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

7th Jul 2018, 3:13 PM
Mr. Jami
Mr. Jami - avatar
5 Answers
+ 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.
8th Jul 2018, 11:55 AM
Swapnil Srivastava
Swapnil Srivastava - avatar
+ 6
oh sorry ‌S‌w‌a‌p‌n‌‌il S‌r‌iv‌‌ast‌av‌a I thaught this was a different language.
8th Jul 2018, 11:56 AM
Agent
Agent - avatar
+ 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.
9th Jul 2018, 9:36 AM
Swapnil Srivastava
Swapnil Srivastava - avatar
+ 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😊😊.
8th Jul 2018, 10:13 AM
Meet Mehta
Meet Mehta - avatar
+ 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? ‌S‌w‌a‌p‌n‌‌il S‌r‌iv‌‌ast‌av‌a
8th Jul 2018, 7:21 PM
Mr. Jami
Mr. Jami - avatar