每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,欢迎关注开源日报。交流QQ群:202790710;微博:https://weibo.com/openingsource;电报群 https://t.me/OpeningSourceOrg


今日推荐开源项目:《如同回到过去 WinFile》传送门:GitHub链接

推荐理由:你能在这个项目里看到一个界面很古老的 windows 的系统文件管理器——包括未更改过的原版和作者自己增强之后的改版和它们两个的源代码。如果你并不对源代码感兴趣而只是想体验一下它的话,里面也放了可供直接打开的应用程序。看习惯了 win10 简单易懂的文件管理之后再回去看看以前的一大堆没有文字的图标,才会发现,技术的普及正是将功能的强大与操作的简单结合起来产生的成果。


今日推荐英文原文:《Intro to Functions in Javascript.》作者:Celestino Salim

原文链接:https://medium.com/@celestino.salim/intro-to-functions-in-javascript-1f20160df176

推荐理由:介绍 JS 中的函数,对于刚刚起步的初学者来说值得一看

Intro to Functions in Javascript.

What are functions?

Functions are “self contained” modules of code that accomplish a specific task. Functions usually “take in” data, process it, and “return” a result. Once a function is written, it can be used over and over and over again. Functions can be “called” from the inside of other functions.

Defining Functions in Javascript

In order to use functions we have to define them, the syntax may vary but most of the time, it will follow this structure:

  • The function keyword
  • A function name
  • A list of parameters
  • A block statement {}
  • An explicit return.
function helloWorld(parameters) {
        return (parameters);
      }

helloWorld("Hello, World!")

This syntax is known as a function declaration, it can be invoked before it is defined because of hoisting. We’re not going to dig deeper into Hoisting, but it is important to know that it’s JavaScript’s default behavior of moving declarations to the top.

Another syntax that we can use to define a function is function Expressions. Notice that in function declaration, the function has a name (helloWorld), while function expressions can be named or anonymous and they’re not hoisted. This means that they cannot be used before defining.

const helloWorld = function(parameters) {
        return (parameters);
      }

helloWorld("Hello, World!")

And Arrow Function Expression is a shorter syntax for writing function expressions.

const helloWorld = (parameters) => parameters

helloWorld("Hello, World!")

Function types in Javascript.

Based on the above we can split functions into 3 different types.

  • Named function

A named function is defined and then can be called when we need it by referencing its name and passing arguments to it.

  • Anonymous function

An anonymous function needs to be tied to something such as a variable or an event, in order to run.

  • Immediately invoked function expression(IIFE).

An IIFE will run as soon as the browser finds it.

In JavaScript, functions are first-class objects. One of the consequences of this is that functions can be passed as arguments to other functions and can also be returned by other functions.

A function that takes other functions as arguments or returns functions as its result is called a higher-order function, and the function that is passed as an argument is called a callback function.

Higher-order functions & Callbacks.

A good example of higher-order functions & callbacks is the built ins .filter &.map methods.

Filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to true.

const drivers = [
{ name: 'Sally',   revenue: 400 },
{ name: 'Annette', revenue: 200 },
{ name: 'Jim',     revenue: 150 }];

function driversWithRevenueOver(drivers, revenue) { 
 return drivers.filter(function(driver) {
  return driver.revenue > revenue 
 })
}

function driverNamesWithRevenueOver(drivers, revenue) {
 return driversWithRevenueOver(drivers,revenue).map(function(driver){ return driver.name })}

The example above have a function called driverNamesWithRevenueOver that returns a function this is what we call higher-order function and the .map function(driver) is the callback function.

Nested Functions

A function can be nested, which means we can define a function inside another function and return it.

function outer(){
 function inner(){
  return "Hello World!";
 }
 return inner;
}

outer()()

Closures

A closure is an inner function made accessible from outside of its parent function with in-scope variables and their values incorporated from the environment in which it was created. In that environment, it has access to its own local variables, to its outer function’s variables and the global variables (declared outside its outer function).

function phrase(name) {
  const hello = "Hello"; 

  function printPhrase() {       
    console.log(hello + " " + name);  
  }

  printPhrase();
}

phrase("Gavin");

In this code example, the printPhrase() function refers to the name variable and the hello parameter of the enclosing (parent) phrase()function. And the result is that, when phrase() is called, printPhrase() successfully uses the variables and parameters of the former to output:

Hello Gavin
undefined

Pure Functions & Impure Functions.

Pure Functions

  1. Always returns the same result if the same arguments are passed in. It does not depend on any state, or data, change during a program’s execution. It must only depend on its input arguments.
  2. The function does not produce any observable side effects such as network requests, input and output devices, or data mutation.
function calculateSquareArea(x) {
   return x * x;
}

Impure functions

This is an impure function because it depends on an external tax variable. A pure function can not depend on outside variables.

const tax = 0.8

function calculateTax(productPrice) {
 return (productPrice * (tax/100)); 
}

The benefits of using pure functions is they are immediately testable. They will always produce the same result if you pass in the same arguments.



每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,欢迎关注开源日报。交流QQ群:202790710;微博:https://weibo.com/openingsource;电报群 https://t.me/OpeningSourceOrg