#163 JavaScript functions

This is an article with the notes that I summarized after learning「Introduction To JavaScript」in Codecademy.

Functions

Functions are written to perform a task. They take data, perform a set of tasks on the data, and then return the result.

How to write a function?

You can write your functions in 3 ways:
const functionName = (parameter) => {write your code here};
const functionName = parameter => write your code here;
function functionName(parameter) {write your code here}

Writing a function in different ways

There is an example showing how to use the first function. Imagine that you own a restaurant and you need a program that can records the orders automatically.

const takeOrder = (foodName) => {
  console.log("Your food is " + foodName);
};

// calling the function
takeOrder("hamburger"); // Your food is hamburger
takeOrder("pizza"); // Your food is pizza
takeOrder("sushi"); // Your food is sushi
const takeOrder = foodName => console.log("Your food is " + foodName);
function takeOrder(foodName) {
  console.log("Your food is " + foodName);
}
Working with Return

The purpose of a function is to take some input, perform some task on that input, and then return a result. The following example can show you how to return a value in a function.

// a function that takes an input of temperature in celsius
// converts from celsius to fahrenheit
// and then return the fahrenheit

function tempConvertor(celsius) {
  let fahrenheit = celsius * 1.8 + 32;
  return fahrenheit;
}

// the function now only returns a value
// in order to print the value to the screen
// the returned value still needs to be logged to the console
console.log(tempConverter(30)); // 86
console.log(tempConverter(0)); // 32

你可能感兴趣的:(#163 JavaScript functions)