+ 1

Function JS properties

If those blocks of code have the sames result, why i should care about attributes? var a = 1; var b = 2; var c = 3; var d= 4; //ex1: function sum() { return(c+d); } console.log(sum(a,b)); //Ex2: function sum(a,b) { return(c+d); } console.log (sum(a,b)); //Ex3: function sum(c,d) { return (c+d); } console.log(sum()); //All results are 7 //So i can put Always function example () {}?? // With no properties?

25th Oct 2022, 4:35 PM
Andrea Fabbri
6 ответов
+ 4
Apollo-Roboto thanks for clearing my doubt :)
25th Oct 2022, 6:12 PM
Sandeep
Sandeep - avatar
+ 3
Its better explained in videotutorials in youtube, search for "var and let differences javascript"
25th Oct 2022, 4:51 PM
arturop200
arturop200 - avatar
+ 3
When you work within one file, sure, it's possible to make it work like that. But not recommended. A well defined function with arguments helps you and other developer to understand what this function needs to give the expected result. It becomes very important to well define your work in larger projects. Also, using var and having functions manipulating those variables globally could accidentally give unexpected results. One function could change it while another is using it. So the proper way to write a sum function would be: function sum(a, b) { return a + b; } I hope this helps :)
25th Oct 2022, 5:04 PM
Apollo-Roboto
Apollo-Roboto - avatar
+ 3
Apollo-Roboto , Andrea Fabbri In example 1, sum function takes no arguments but it is called with two arguments (a,b). In example 3, sum() take two arguments but called with zero. How does this work in javascript? Something like this gives error in python (unless keyword arguments)
25th Oct 2022, 5:33 PM
Sandeep
Sandeep - avatar
+ 1
Tnx You very much!
25th Oct 2022, 5:21 PM
Andrea Fabbri
+ 1
Sandeep in javascript, if you call with missing arguments, their values will be undefined. if you call with too many arguments, the extra will be discarded.
25th Oct 2022, 5:58 PM
Apollo-Roboto
Apollo-Roboto - avatar