Functions in JavaScript

Tram Ho

Article purpose

  • Understand function declaration syntax
  • Understand how to use functions in JavaScript

Content

A function in JavaScript is a block of code designed to perform a specific task.

Function declaration syntax in JavaScript

A JavaScript function defined with the keyword function, followed by the function name, followed by parentheses ().

Parentheses can include comma-separated parameter names.

Function names can contain letters, numbers, underscores, and dollar signs (the same rules as variables). Eg:

  • The parameters of the function are listed inside parentheses ().
  • The arguments of a function are the values the function receives when it is called.
  • Inside the function, the arguments (parameters) act like local variables.

When is the function called?

The function is called:

  • When an event occurs (when the user clicks a button)
  • When it is called from JavaScript code.
  • Auto call.

Return function

When JavaScript encounters the keyword return, function will stop executing. Functions usually compute a value and return it. Eg:

Why use functions?

Functions help us to reuse code to make it easier to read and maintain. You can use the function multiple times and with different parameters will return different results. Eg:

Results returned : function toCelsius(f) { return (5/9) \* (f-32); }

Share the news now