# JavaScript 入门 Day 4 **Published by:** [aow](https://paragraph.com/@ashonthewall/) **Published on:** 2022-03-17 **URL:** https://paragraph.com/@ashonthewall/javascript-day-4 ## Content 今天从学function开始。 Write Reusable JavaScript with Functions 之前说过varialbe类似一个装数据的盒子,那么,functions就是一个装算法步骤的盒子。 每次调用functions,等于按照function规定好的12345…这些步骤从头到尾来一遍。 所以,function是可以反复使用的。function reusableFunction(){ console.log("Hi World"); } 这个function里面有一个步骤,就是输出 “Hi World”这两个单词。 下次需要输出这两个单词的时候,只需要调用这个functionreusableFunction(); Passing Values to Functions with Arguments function的这个( )里面可以预留位置给parameters,这些parameters之后就可以直接带入到function的使用中了。 比如写一个简单的加法functionfunction sum(x,y){ console.log(x + y); } 这个sum 其实就是个+的功能。 运行它sum(1, 2); 等于是运行了 1 + 2, 输出就是3。 Return a Value from a Function with Return 当然,function不一定要输出结果,还可以return。 return 是返回结果暂时储存,但不输出。function timesFive (num){ return num * 5; } timesFive(5); 返回数值5,但不会打印输出。 Global Scope and Functions Local Scope and Functions variable分两种,一种是在function里面定义的,另一种是在function外面定义的。 function外面定义的variable称为global variable,global variable其它的function也可以调用。 function内定义的variable称为local variable,只在function内可以调用。 注意:没有用let 或 const定义的variable自动成为global variable,无论是function内外。所以为了避免歧义,请总是使用let 或 const来定义variable。 Global vs. Local Scope in Functions 当local variable和global variable同名的时候,function会优先调用function内的variable。 Understanding Undefined Value returned from a Function 如果一个function里面没有return value,那么function还是会运行,但是return value就会显示undefined. Assignment with a Returned Value 很好理解。 在这些地方可以找到我 https://discord.gg/madnfts https://discord.gg/Z25p8gkZWx ## Publication Information - [aow](https://paragraph.com/@ashonthewall/): Publication homepage - [All Posts](https://paragraph.com/@ashonthewall/): More posts from this publication - [RSS Feed](https://api.paragraph.com/blogs/rss/@ashonthewall): Subscribe to updates