Lambda School Pre-course 13: Learn why we use JavaScript Functions and be able to write correct function syntax

There are nine units in Lambda School’s Full Stack Web Development Pre-course. I’m going to summarize what the pre-course covers for each of them. This material is basically ground-floor information that students need to know before they start the full course.

precourse13

Learn why we use JavaScript Functions and be able to write correct function syntax

A function is a named section of code that can be called and reused. They can optionally take arguments (parameters), which are values that are passed to the function to be processed. They can also optionally return a value back.

Although they’re generally used to define code that can be called multiple times (to reduce having to rewrite that same code repeatedly), book 1 of You Don’t Know JS offers another tip: they can also be used to organize related bits of code into named collections. I like sorting items and placing the ones that are alike together, so this tip is right up my alley. ;)

Functions adhere to a school of thought in programming called DRY, or Don’t Repeat Yourself. It helps lead to lean code. They also have their own scope, so variables assigned within a function are not available outside of the function – although they can make use of global variables.

How to Write a Function

There are three ways to build a function. The pre-course focuses on the first one. The other two variations have their own uses and behaviors and are covered in later lessons.

function myFunc() {}

const anotherFunc = function () {};

const yetAnother = () => {};

Anatomy of a Function

function myFunc() {}

A function begins with the function keyword. This is called defining or declaring a function, and tells the computer that the code to follow is part of a function block. Next comes the name of the function. The name should describe what the function does. Then comes an opening and closing parenthesis, and finally opening and closing brackets. The actual code for the function will be placed between the brackets.

function logsHello() { console.log(‘hello’); }

logsHello();

In the above example, a function called logsHello is declared. Its only line of code instructs it to console.log the word hello. In order to run a function, it needs to be called with its name and a set of parenthesis. This is the standard syntax to run a function. The parenthesis allow data, such as variables, to be sent to the function so it can perform operations on them. The above example does not send any data to the function, however, as its only purpose is to say hello via the console.

2 thoughts on “Lambda School Pre-course 13: Learn why we use JavaScript Functions and be able to write correct function syntax

Leave a comment