JavaScript Functions

Functions are objects in JavaScript and can be used as variables in expressions, passed to other functions, or treated like numbers or strings.

The traditional function declaration has several parts:

  • function keyword;
  • name of the function;
  • function body, which contains JavaScript statements; and
  • return statement

Functions may have "parameters", values passed to the function from a calling program, but they are not required. To execute a function, it must be "called". This will run the statements in the body of the function. Read this article about how functions are defined and used. After reading this article, consider these questions: 

  • What is the difference between local, global, and lexical scoping?
  • Can functions be called with different numbers of parameters?
  • What is returned if a function does not have a "return" statement?

Functions

"People think that computer science is the art of geniuses but the actual reality is the opposite, just many people doing things that build on each other, like a wall of mini stones". -- Donald Knuth



Functions are the bread and butter of JavaScript programming. The concept of wrapping a piece of program in a value has many uses. It gives us a way to structure larger programs, to reduce repetition, to associate names with subprograms, and to isolate these subprograms from each other.

The most obvious application of functions is defining new vocabulary. Creating new words in prose is usually bad style. But in programming, it is indispensable.

Typical adult English speakers have some 20,000 words in their vocabulary. Few programming languages come with 20,000 commands built in. And the vocabulary that is available tends to be more precisely defined, and thus less flexible, than in human language. Therefore, we usually have to introduce new concepts to avoid repeating ourselves too much.


Source: Marijn Haverbeke, https://eloquentjavascript.net/03_functions.html
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial 3.0 License.