JavaScript Functions

Functions are "self contained" modules of code that accomplish a specific task. It contains instructions used to create the output from its input. To use a function, you must define it somewhere in the scope from which you wish to call it. Most programming languages come with a prewritten set of functions that are kept in a library. You can also write your own functions to perform specialized tasks . Javascript functions are considered as first-class objects, because they can be manipulated like any other object in the language.

Function Declaration

A function declaration is made of function keyword , followed by a function name, a list of parameters and a pair of curly braces {} that delimits the body code. Function names are case sensitive , that is a function name "doThis()" is not same as "DoThis()"

The parameter is optional , you can write function without parameters.

Calling JavaScript functions

You can call Javascript functions by simply call the function name.

run this source code Try it Yourself

JavaScript Function Parameters

A JavaScript function can take multiple parameters separated by comma. The parameters pass to the function will captured inside the function and any manipulation can be done over those arguments.

run this source code Try it Yourself

JavaScript Function with Return Value

Javascript functions have the ability to return a value from a function to the code that called it. For example, you can pass two numbers in a function and then you can expect the function to return their sum in your calling program.

run this source code Try it Yourself

Function hoisting

Hoisting is JavaScript's default behaviour of moving all declarations to the top of the current scope . Declarations are moved to the top of the current scope by the JavaScript interpreter , meaning the top of the current function or scripts. A JavaScript function can be invoked before its declaration. This works because the JavaScript engine implicitly hoists the function to the top so that they are visible throughout the program.

In the example ablve, the function named callMe() is parsed and evaluated before any other code is run.
 (C) 2022    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap  | Terms  | About