DEV Community

Cover image for Functions in Javascipt
vidhya murali
vidhya murali

Posted on

Functions in Javascipt

Functions

  • Functions are reusable code blocks designed for particular tasks
  • Functions are executed when they are called or invoked
  • Functions are fundamental in all programming languages.

Why Use Functions?

Functions help you to:

  • Reuse code (write once, run many times)
  • Organize code into smaller parts
  • Make code easier to read and maintain

What Does a Function Look Like?

A function can be created with the function keyword, a name, and parentheses.

The code to run is written inside curly brackets

function sayHello() {
return "Hello World";
}

Functions Run When You Call Them

JavaScript Function Syntax

  • A function definition is not an executable statement.
  • It is not common to end a function definition with a semicolon.
  • Semicolons are used to separate executable JavaScript statements.

A Function Can Be Used Many Times

A big benefit is that you can call the same function whenever you need it.

Note that values returned from functions can be stored in variables.

Local Variables

Variables declared within a JavaScript function, become LOCAL to the function.

Local variables can only be accessed from within the function

Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.
Local variables are created when a function starts, and deleted when the function is completed.

Functions Used as Variables

Functions can be used as variables, in all types of formulas, assignments, and calculations.

let x = toCelsius(77);
let text = "The temperature is " + x + " Celsius";

Function Input and Output

The most useful functions work like this:

  • Parameters - some values are sent to the function
  • Arguments - some values are received by the function
  • Function Code - some work is done inside the function
  • Return Output - some value is returned from the function

Reference :

Top comments (0)