Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST TOOLS

Basic JavaScript

JS Tutorial JS Introduction JS Where To JS Output

JS Syntax

JS Syntax JS Statements JS Comments JS Variables JS Let JS Const JS Types

JS Operators

JS Operators JS Arithmetic JS Assignment JS Comparisons JS Conditional JS If JS If Else JS Ternary JS Switch JS Booleans JS Logical

JS Loops

JS Loops JS Loop for JS Loop while JS Break JS Continue JS Control Flow

JS Strings

JS Strings JS String Templates JS String Methods JS String Search JS String Reference

JS Numbers

JS Numbers JS Number Methods JS Number Properties JS Number Reference JS Bitwise JS BigInt

JS Functions

Function Path Function Intro Function Invocation Function Parameters Function Returns Function Arguments Function Expressions Function Arrow Function Quiz

JS Objects

Object Path Object Intro Object Properties Object Methods Object this Object Display Object Constructors

JS Scope

JS Scope JS Code Blocks JS Hoisting JS Strict Mode

JS Dates

JS Dates JS Date Formats JS Date Get JS Date Set JS Date Methods

JS Arrays

JS Arrays JS Array Methods JS Array Search JS Array Sort JS Array Iterations JS Array Reference JS Array Const

JS Sets

JS Sets JS Set Methods JS Set Logic JS Set WeakSet JS Set Reference

JS Maps

JS Maps JS Map Methods JS Map WeakMap JS Map Reference

JS Iterations

JS Loops JS Iterables JS Iterators JS Generators

JS Math

JS Math JS Math Reference JS Math Random

JS RexExp

JS RegExp JS RegExp Flags JS RegExp Classes JS RegExp Metachars JS RegExp Assertions JS RegExp Quantifiers JS RegExp Patterns JS RegExp Objects JS RegExp Methods

JS Data Types

JS Destructuring JS Data Types JS Primitive Data JS Object Types JS typeof JS toString JS Type Conversion

JS Errors

JS Errors Intro JS Errors Silent JS Error Statements JS Error Object

JS Debugging

Debugging Intro Debugging Console Debugging Breakpoints Debugging Errors Debugging Async Debugging Reference

JS Conventions

JS Style Guide JS Best Practices JS Mistakes JS Performance

JS References

JS Statements JS Reserved Keywords JS Operators JS Precedence

JS Versions

JS 2026 JS 2025 JS 2024 JS 2023 JS 2022 JS 2021 JS 2020 JS 2019 JS 2018 JS 2017 JS 2016 JS Versions JS 2015 (ES6) JS 2009 (ES5) JS 1999 (ES3) JS IE / Edge JS History

JS HTML

JS HTML DOM JS Events JS Projects New

JS Advanced

JS Temporal  New JS Functions JS Objects JS Classes JS Asynchronous JS Modules JS Meta & Proxy JS Typed Arrays JS DOM Navigation JS Windows JS Web APIs JS AJAX JS JSON JS jQuery JS Graphics JS Examples JS Reference


JavaScript Functions

Functions are Code Blocks

Functions are reusable code blocks designed to perform a particular task.

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.

Example

A one liner:

function sayHello() { return "Hello World"; }
or more common:
function sayHello() {
  return "Hello World";
}

Note

The function above does not do anything.

It has to be called first.


Functions Run When You Call Them

To run a function, you call it by using its name followed by parentheses like sayHello():

Example

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

let message = sayHello();
Try it Yourself »

Note

() means execute now.



JavaScript Function Syntax

function name( p1, p2, ... ) {
  // code to be executed
}

Functions are defined with the function keyword:

  • followed by the function name
  • followed by parentheses ( )
  • followed by brackets { }

The function name follows the naming rules for variables.

Optional parameters are listed inside parentheses: ( p1, p2, ... )

Code to be executed is listed inside curly brackets: { }

Functions can return an optional value back to the caller.

Example

Function to multiply two numbers:

function multiply(a, b) {
  return a * b;
}
Try it Yourself »

Note

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.

Example

function add(a, b) {
  return a + b;
}

let sum1 = add(5, 5);
let sum2 = add(50, 50);
Try it Yourself »

Note

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.

Example

// code here can NOT use carName

function myFunction() {
  let carName = "Volvo";
  // code here CAN use carName
}

// code here can NOT use carName
Try it Yourself »

Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.

Note

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.

Example

Instead of using a variable to store the return value of a function:

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

You can use the function directly, as a variable value:

let text = "The temperature is " + toCelsius(77) + " Celsius";
Try it Yourself »

Why Functions?

Functions enable better code organization and efficiency.

With functions you can reuse the same code many times.

The same code, with different input, can produce different results.


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

In the next chapters, you will learn more about input and return values.


Next Chapter

Calling JavaScript Functions

  • Functions are executed when they are called or invoked
  • You call a function by adding parentheses to its name like: name()


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.

-->