JavaScript Functions

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9

Introduction

Functions in JavaScript provide organized, reusable code to perform a set of actions. Functions simplify the coding process, prevent redundant logic, and make code easier to follow. This topic describes the declaration and utilization of functions, arguments, parameters, return statements and scope in JavaScript.

Syntax

  • function example(x) { return x }

  • var example = function (x) { return x }

  • (function() { ... })(); // Immediately Invoked Function Expression (IIFE)

  • var instance = new Example(x);

  • Methods

  • fn.apply(valueForThis[, arrayOfArgs])

  • fn.bind(valueForThis[, arg1[, arg2, ...]])

  • fn.call(valueForThis[, arg1[, arg2, ...]])

  • ES2015+ (ES6+):

  • const example = x => { return x }; // Arrow function explicit return

  • const example = x => x; // Arrow function implicit return

  • const example = (x, y, z) => { ... } // Arrow function multiple arguments

  • (() => { ... })(); // IIFE using an arrow function

Remarks

For information on arrow functions, please view the Arrow Functions documentation.



Got any JavaScript Question?