Trying to write a function that returns the average of it's two arguments. What's wrong with my code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Trying to write a function that returns the average of it's two arguments. What's wrong with my code?

This is my first steps in JS, but I have some skills in Python, so it's helping me a lot right now. However, my code doesn't work, while all syntax seems to be fine. I'm not asking to write the code for me, just point me, please, on my mistakes. Thank you in advance! function avg(num1, num2, num3) { num1=56 num2=43 num3=(num1+num2)/2 console.log(num3);

12th Jun 2017, 5:04 PM
DIY Mods
DIY Mods - avatar
7 Answers
+ 3
first of all u haven't used semicolons use them at the end of declaration of a variable
12th Jun 2017, 5:07 PM
_Retr0/-
_Retr0/- - avatar
+ 3
and you should have actually used return function
12th Jun 2017, 5:07 PM
_Retr0/-
_Retr0/- - avatar
12th Jun 2017, 5:12 PM
_Retr0/-
_Retr0/- - avatar
+ 1
won't work,you have to specify the calculations to be carried out in the return keyword
12th Jun 2017, 5:50 PM
_Retr0/-
_Retr0/- - avatar
+ 1
function avg(num1, num2) { console.log(num1+num2)/2 } avg(56,43) // @DIY Mods, you have to put this in order to run the function ---- Better way using arguments as input parameter so no constrain to 2 numbers function avg() { nums = Array.from(arguments) console.log(nums.reduce((acc,a)=>acc+=a)/nums.length) } avg(56,43) avg(56,43,1) // * @_Retr0/-, please note that Javascript statements ended with semicolon (;) is not required now.
13th Jun 2017, 5:10 AM
Calviղ
Calviղ - avatar
0
I can not use html or css at all. Only JS. How about this: function avg(num1, num2, avg){ num1=34; num2=54; avg=(num1+num2)/2; return avg;
12th Jun 2017, 5:45 PM
DIY Mods
DIY Mods - avatar
0
Ok, it works this way: var x = myFunction(65, -9); function myFunction(a, b) { x = (a+b)/2; console.log(x) } But how can I get an output with return, without var x = myFunction(65, -9); ? I can assign the values to 'a'&'b' to make it like this: function myFunction(a, b) { a = 44 b = 67 x = (a+b)/2; console.log(x) } But it doesn't work
12th Jun 2017, 10:00 PM
DIY Mods
DIY Mods - avatar