Web Analytics

JavaScript Functions

Beginner ~15 min read

What is a Function?

A function is a block of code designed to perform a particular task. A function is executed when "something" invokes it (calls it).

HTML
CSS
JS

Function Expressions

A function can also be defined using an expression. A function expression can be stored in a variable.

const square = function(number) {
  return number * number;
};

let x = square(4); // x gets the value 16

Arrow Functions

Arrow functions (introduced in ES6) allow for a shorter syntax for writing function expressions.

HTML
CSS
JS
Implicit Return: If an arrow function has a single expression in its body, you can omit the curly braces {} and the return keyword.

Parameters and Arguments

Parameters are the names listed in the function definition.
Arguments are the real values passed to the function.

HTML
CSS
JS

Summary

  • Functions are reusable blocks of code.
  • Functions can return values using the return keyword.
  • Variables declared inside a function are local to the function.
  • Arrow functions provide a concise syntax for writing functions.

Quick Quiz

Which syntax is correct for an arrow function?

A
function() => {}
B
() => {}
C
=> function() {}
D
arrow() {}