🕷️ Crawler Inspector

URL Lookup

Direct Parameter Lookup

Raw Queries and Responses

1. Shard Calculation

Query:
Response:
Calculated Shard: 147 (from laksa184)

2. Crawled Status Check

Query:
Response:

3. Robots.txt Check

Query:
Response:

4. Spam/Ban Check

Query:
Response:

5. Seen Status Check

ℹ️ Skipped - page is already crawled

đź“„
INDEXABLE
âś…
CRAWLED
2 days ago
🤖
ROBOTS ALLOWED

Page Info Filters

FilterStatusConditionDetails
HTTP statusPASSdownload_http_code = 200HTTP 200
Age cutoffPASSdownload_stamp > now() - 6 MONTH0.1 months ago
History dropPASSisNull(history_drop_reason)No drop reason
Spam/banPASSfh_dont_index != 1 AND ml_spam_score = 0ml_spam_score=0
CanonicalPASSmeta_canonical IS NULL OR = '' OR = src_unparsedNot set

Page Details

PropertyValue
URLhttps://www.tutorialrepublic.com/javascript-tutorial/javascript-functions.php
Last Crawled2026-04-15 08:17:20 (2 days ago)
First Indexed2018-08-06 23:43:09 (7 years ago)
HTTP Status Code200
Meta TitleDefining and Calling Functions in JavaScript - Tutorial Republic
Meta Descriptionnull
Meta Canonicalnull
Boilerpipe Text
Advertisements In this tutorial you will learn how to define and call a function in JavaScript. What is Function? A function is a group of statements that perform specific tasks and can be kept and maintained separately form main program. Functions provide a way to create reusable code packages which are more portable and easier to debug. Here are some advantages of using functions: Functions reduces the repetition of code within a program — Function allows you to extract commonly used block of code into a single component. Now you can perform the same task by calling this function wherever you want within your script without having to copy and paste the same block of code again and again. Functions makes the code much easier to maintain — Since a function created once can be used many times, so any changes made inside a function automatically implemented at all the places without touching the several files. Functions makes it easier to eliminate the errors — When the program is subdivided into functions, if any error occur you know exactly what function causing the error and where to find it. Therefore, fixing errors becomes much easier. The following section will show you how to define and call functions in your scripts. Defining and Calling a Function The declaration of a function start with the function keyword, followed by the name of the function you want to create, followed by parentheses i.e. () and finally place your function's code between curly brackets {} . Here's the basic syntax for declaring a function: function functionName() {      } Here is a simple example of a function, that will show a hello message: // Defining function function sayHello ( ) { alert ( "Hello, welcome to this website!" ) ; } // Calling function sayHello ( ) ; // 0utputs: Hello, welcome to this website! Once a function is defined it can be called (invoked) from anywhere in the document, by typing its name followed by a set of parentheses, like sayHello() in the example above. Note: A function name must start with a letter or underscore character not with a number, optionally followed by the more letters, numbers, or underscore characters. Function names are case sensitive, just like variable names. Adding Parameters to Functions You can specify parameters when you define your function to accept input values at run time. The parameters work like placeholder variables within a function; they're replaced at run time by the values (known as argument) provided to the function at the time of invocation. Parameters are set on the first line of the function inside the set of parentheses, like this: function functionName( parameter1 , parameter2 , parameter3 ) {      } The displaySum() function in the following example takes two numbers as arguments, simply add them together and then display the result in the browser. // Defining function function displaySum ( num1 , num2 ) { let total = num1 + num2 ; alert ( total ) ; } // Calling function displaySum ( 6 , 20 ) ; // 0utputs: 26 displaySum ( - 5 , 17 ) ; // 0utputs: 12 You can define as many parameters as you like. However for each parameter you specify, a corresponding argument needs to be passed to the function when it is called, otherwise its value becomes undefined . Let's consider the following example: // Defining function function showFullname ( firstName , lastName ) { alert ( firstName + " " + lastName ) ; } // Calling function showFullname ( "Clark" , "Kent" ) ; // 0utputs: Clark Kent showFullname ( "John" ) ; // 0utputs: John undefined Default Values for Function Parameters ES6 With ES6, now you can specify default values to the function parameters. This means that if no arguments are provided to function when it is called these default parameters values will be used. This is one of the most awaited features in JavaScript. Here's an example: function sayHello ( name = 'Guest' ) { alert ( 'Hello, ' + name ) ; } sayHello ( ) ; // 0utputs: Hello, Guest sayHello ( 'John' ) ; // 0utputs: Hello, John While prior to ES6, to achieve the same we had to write something like this: function sayHello ( name ) { let name = name || 'Guest' ; alert ( 'Hello, ' + name ) ; } sayHello ( ) ; // 0utputs: Hello, Guest sayHello ( 'John' ) ; // 0utputs: Hello, John To learn about other ES6 features, please check out the JavaScript ES6 features chapter. Returning Values from a Function A function can return a value back to the script that called the function as a result using the return statement. The value may be of any type, including arrays and objects. The return statement usually placed as the last line of the function before the closing curly bracket and ends it with a semicolon, as shown in the following example. // Defining function function getSum ( num1 , num2 ) { let total = num1 + num2 ; return total ; } // Displaying returned value alert ( getSum ( 6 , 20 ) ) ; // 0utputs: 26 alert ( getSum ( - 5 , 17 ) ) ; // 0utputs: 12 A function can not return multiple values. However, you can obtain similar results by returning an array of values, as demonstrated in the following example. // Defining function function divideNumbers ( dividend , divisor ) { let quotient = dividend / divisor ; let arr = [ dividend , divisor , quotient ] ; return arr ; } // Store returned value in a variable let all = divideNumbers ( 10 , 2 ) ; // Displaying individual values alert ( all [ 0 ] ) ; // 0utputs: 10 alert ( all [ 1 ] ) ; // 0utputs: 2 alert ( all [ 2 ] ) ; // 0utputs: 5 Working with Function Expressions The syntax that we've used before to create functions is called function declaration. There is another syntax for creating a function that is called a function expression. // Function Declaration function getSum ( num1 , num2 ) { let total = num1 + num2 ; return total ; } // Function Expression let getSum = function ( num1 , num2 ) { let total = num1 + num2 ; return total ; } ; Once function expression has been stored in a variable, the variable can be used as a function: let getSum = function ( num1 , num2 ) { let total = num1 + num2 ; return total ; } ; alert ( getSum ( 5 , 10 ) ) ; // 0utputs: 15 let sum = getSum ( 7 , 25 ) ; alert ( sum ) ; // 0utputs: 32 Note: There is no need to put a semicolon after the closing curly bracket in a function declaration. But function expressions, on the other hand, should always end with a semicolon. Tip: In JavaScript functions can be stored in variables, passed into other functions as arguments, passed out of functions as return values, and constructed at run-time. The syntax of the function declaration and function expression looks very similar, but they differ in the way they are evaluated, check out the following example: declaration ( ) ; // Outputs: Hi, I'm a function declaration! function declaration ( ) { alert ( "Hi, I'm a function declaration!" ) ; } expression ( ) ; // Uncaught TypeError: undefined is not a function let expression = function ( ) { alert ( "Hi, I'm a function expression!" ) ; } ; As you can see in the above example, the function expression threw an exception when it was invoked before it is defined, but the function declaration executed successfully. JavaScript parse declaration function before the program executes. Therefore, it doesn't matter if the program invokes the function before it is defined because JavaScript has hoisted the function to the top of the current scope behind the scenes. The function expression is not evaluated until it is assigned to a variable; therefore, it is still undefined when invoked. ES6 has introduced even shorter syntax for writing function expression which is called arrow function , please check out the JavaScript ES6 features chapter to learn more about it. Understanding the Variable Scope However, you can declare the variables anywhere in JavaScript. But, the location of the declaration determines the extent of a variable's availability within the JavaScript program i.e. where the variable can be used or accessed. This accessibility is known as variable scope . By default, variables declared within a function have local scope that means they cannot be viewed or manipulated from outside of that function, as shown in the example below: // Defining function function greetWorld ( ) { let greet = "Hello World!" ; alert ( greet ) ; } greetWorld ( ) ; // Outputs: Hello World! alert ( greet ) ; // Uncaught ReferenceError: greet is not defined However, any variables declared in a program outside of a function has global scope i.e. it will be available to all script, whether that script is inside a function or outside. Here's an example: let greet = "Hello World!" ; // Defining function function greetWorld ( ) { alert ( greet ) ; } greetWorld ( ) ; // Outputs: Hello World! alert ( greet ) ; // Outputs: Hello World! Advertisements
Markdown
[![TutorialRepublic](https://www.tutorialrepublic.com/lib/images/logo.svg)](https://www.tutorialrepublic.com/) [HOME](https://www.tutorialrepublic.com/ "Home Page") [HTML5](https://www.tutorialrepublic.com/html-tutorial/ "HTML Tutorial") [CSS3](https://www.tutorialrepublic.com/css-tutorial/ "CSS Tutorial") [JAVASCRIPT](https://www.tutorialrepublic.com/javascript-tutorial/ "JavaScript Tutorial") [JQUERY](https://www.tutorialrepublic.com/jquery-tutorial/ "jQuery Tutorial") [BOOTSTRAP5](https://www.tutorialrepublic.com/twitter-bootstrap-tutorial/ "Bootstrap 5 Tutorial") [v4.6](https://www.tutorialrepublic.com/twitter-bootstrap-4-tutorial/ "Bootstrap 4.6 Tutorial") [PHP7](https://www.tutorialrepublic.com/php-tutorial/ "PHP Tutorial") [SQL](https://www.tutorialrepublic.com/sql-tutorial/ "SQL Tutorial") [REFERENCES](https://www.tutorialrepublic.com/references.php "Web References") [EXAMPLES](https://www.tutorialrepublic.com/practice-examples.php "Practice Examples and Demos") [FAQ](https://www.tutorialrepublic.com/faq.php "Frequently Asked Questions and Answers") [SNIPPETS](https://www.tutorialrepublic.com/snippets/gallery.php "Bootstrap Code Snippets") [Online HTML Editor](https://www.tutorialrepublic.com/codelab.php) JAVASCRIPT BASIC [JS Introduction](https://www.tutorialrepublic.com/javascript-tutorial/) [JS Getting Started](https://www.tutorialrepublic.com/javascript-tutorial/javascript-get-started.php) [JS Syntax](https://www.tutorialrepublic.com/javascript-tutorial/javascript-syntax.php) [JS Variables](https://www.tutorialrepublic.com/javascript-tutorial/javascript-variables.php) [JS Generating Output](https://www.tutorialrepublic.com/javascript-tutorial/javascript-generating-output.php) [JS Data Types](https://www.tutorialrepublic.com/javascript-tutorial/javascript-data-types.php) [JS Operators](https://www.tutorialrepublic.com/javascript-tutorial/javascript-operators.php) [JS Events](https://www.tutorialrepublic.com/javascript-tutorial/javascript-events.php) [JS Strings](https://www.tutorialrepublic.com/javascript-tutorial/javascript-strings.php) [JS Numbers](https://www.tutorialrepublic.com/javascript-tutorial/javascript-numbers.php) [JS If…Else](https://www.tutorialrepublic.com/javascript-tutorial/javascript-if-else-statements.php) [JS Switch…Case](https://www.tutorialrepublic.com/javascript-tutorial/javascript-switch-case-statements.php) [JS Arrays](https://www.tutorialrepublic.com/javascript-tutorial/javascript-arrays.php) [JS Sorting Arrays](https://www.tutorialrepublic.com/javascript-tutorial/javascript-sorting-arrays.php) [JS Loops](https://www.tutorialrepublic.com/javascript-tutorial/javascript-loops.php) [JS Functions](https://www.tutorialrepublic.com/javascript-tutorial/javascript-functions.php) [JS Objects](https://www.tutorialrepublic.com/javascript-tutorial/javascript-objects.php) JAVASCRIPT & DOM [JS DOM Nodes](https://www.tutorialrepublic.com/javascript-tutorial/javascript-dom-nodes.php) [JS DOM Selectors](https://www.tutorialrepublic.com/javascript-tutorial/javascript-dom-selectors.php) [JS DOM Styling](https://www.tutorialrepublic.com/javascript-tutorial/javascript-dom-styling.php) [JS DOM Get Set Attributes](https://www.tutorialrepublic.com/javascript-tutorial/javascript-dom-get-set-attributes.php) [JS DOM Manipulation](https://www.tutorialrepublic.com/javascript-tutorial/javascript-dom-manipulation.php) [JS DOM Navigation](https://www.tutorialrepublic.com/javascript-tutorial/javascript-dom-navigation.php) JAVASCRIPT & BOM [JS Window](https://www.tutorialrepublic.com/javascript-tutorial/javascript-window.php) [JS Screen](https://www.tutorialrepublic.com/javascript-tutorial/javascript-window-screen.php) [JS Location](https://www.tutorialrepublic.com/javascript-tutorial/javascript-window-location.php) [JS History](https://www.tutorialrepublic.com/javascript-tutorial/javascript-window-history.php) [JS Navigator](https://www.tutorialrepublic.com/javascript-tutorial/javascript-window-navigator.php) [JS Dialog Boxes](https://www.tutorialrepublic.com/javascript-tutorial/javascript-dialog-boxes.php) [JS Timers](https://www.tutorialrepublic.com/javascript-tutorial/javascript-timers.php) JAVASCRIPT ADVANCED [JS Date and Time](https://www.tutorialrepublic.com/javascript-tutorial/javascript-date-and-time.php) [JS Math Operations](https://www.tutorialrepublic.com/javascript-tutorial/javascript-math-operations.php) [JS Type Conversions](https://www.tutorialrepublic.com/javascript-tutorial/javascript-type-conversions.php) [JS Event Listeners](https://www.tutorialrepublic.com/javascript-tutorial/javascript-event-listeners.php) [JS Event Propagation](https://www.tutorialrepublic.com/javascript-tutorial/javascript-event-propagation.php) [JS Borrowing Methods](https://www.tutorialrepublic.com/javascript-tutorial/javascript-borrowing-methods.php) [JS Hoisting Behavior](https://www.tutorialrepublic.com/javascript-tutorial/javascript-hoisting.php) [JS Closures](https://www.tutorialrepublic.com/javascript-tutorial/javascript-closures.php) [JS Strict Mode](https://www.tutorialrepublic.com/javascript-tutorial/javascript-strict-mode.php) [JS JSON Parsing](https://www.tutorialrepublic.com/javascript-tutorial/javascript-json-parsing.php) [JS Error Handling](https://www.tutorialrepublic.com/javascript-tutorial/javascript-error-handling.php) [JS Regular Expressions](https://www.tutorialrepublic.com/javascript-tutorial/javascript-regular-expressions.php) [JS Form Validation](https://www.tutorialrepublic.com/javascript-tutorial/javascript-form-validation.php) [JS Cookies](https://www.tutorialrepublic.com/javascript-tutorial/javascript-cookies.php) [JS AJAX Requests](https://www.tutorialrepublic.com/javascript-tutorial/javascript-ajax.php) [JS ES6 Features](https://www.tutorialrepublic.com/javascript-tutorial/javascript-es6-features.php) JAVASCRIPT EXAMPLES [JS Practice Examples](https://www.tutorialrepublic.com/javascript-examples.php) [JS FAQ's Answers](https://www.tutorialrepublic.com/faq.php#javascript-jquery) JAVASCRIPT REFERENCE - JS Properties and Methods - [JS Array Object](https://www.tutorialrepublic.com/javascript-reference/javascript-array-object.php) - [JS Boolean Object](https://www.tutorialrepublic.com/javascript-reference/javascript-boolean-object.php) - [JS Date Object](https://www.tutorialrepublic.com/javascript-reference/javascript-date-object.php) - [JS Math Object](https://www.tutorialrepublic.com/javascript-reference/javascript-math-object.php) - [JS Number Object](https://www.tutorialrepublic.com/javascript-reference/javascript-number-object.php) - [JS String Object](https://www.tutorialrepublic.com/javascript-reference/javascript-string-object.php) - [JS Reserved Keywords](https://www.tutorialrepublic.com/javascript-reference/javascript-reserved-keywords.php) - [More references](https://www.tutorialrepublic.com/references.php) Advertisements # JavaScript Functions In this tutorial you will learn how to define and call a function in JavaScript. ## What is Function? A function is a group of statements that perform specific tasks and can be kept and maintained separately form main program. Functions provide a way to create reusable code packages which are more portable and easier to debug. Here are some advantages of using functions: - **Functions reduces the repetition of code within a program** — Function allows you to extract commonly used block of code into a single component. Now you can perform the same task by calling this function wherever you want within your script without having to copy and paste the same block of code again and again. - **Functions makes the code much easier to maintain** — Since a function created once can be used many times, so any changes made inside a function automatically implemented at all the places without touching the several files. - **Functions makes it easier to eliminate the errors** — When the program is subdivided into functions, if any error occur you know exactly what function causing the error and where to find it. Therefore, fixing errors becomes much easier. The following section will show you how to define and call functions in your scripts. ## Defining and Calling a Function The declaration of a function start with the `function` keyword, followed by the name of the function you want to create, followed by parentheses i.e. `()` and finally place your function's code between curly brackets `{}`. Here's the basic syntax for declaring a function: function functionName() { // Code to be executed } Here is a simple example of a function, that will show a hello message: #### Example [Try this code »](https://www.tutorialrepublic.com/codelab.php?topic=javascript&file=define-and-call-a-function "Try this code using online Editor") ``` // Defining function function sayHello() { alert("Hello, welcome to this website!"); } // Calling function sayHello(); // 0utputs: Hello, welcome to this website! ``` Once a function is defined it can be called (invoked) from anywhere in the document, by typing its name followed by a set of parentheses, like `sayHello()` in the example above. **Note:** A function name must start with a letter or underscore character not with a number, optionally followed by the more letters, numbers, or underscore characters. Function names are case sensitive, just like variable names. *** ## Adding Parameters to Functions You can specify parameters when you define your function to accept input values at run time. The parameters work like placeholder variables within a function; they're replaced at run time by the values (known as argument) provided to the function at the time of invocation. Parameters are set on the first line of the function inside the set of parentheses, like this: function functionName(*parameter1*, *parameter2*, *parameter3*) { // Code to be executed } The `displaySum()` function in the following example takes two numbers as arguments, simply add them together and then display the result in the browser. #### Example [Try this code »](https://www.tutorialrepublic.com/codelab.php?topic=javascript&file=add-parameters-to-a-function "Try this code using online Editor") ``` // Defining function function displaySum(num1, num2) { let total = num1 + num2; alert(total); } // Calling function displaySum(6, 20); // 0utputs: 26 displaySum(-5, 17); // 0utputs: 12 ``` You can define as many parameters as you like. However for each parameter you specify, a corresponding argument needs to be passed to the function when it is called, otherwise its value becomes `undefined`. Let's consider the following example: #### Example [Try this code »](https://www.tutorialrepublic.com/codelab.php?topic=javascript&file=pass-arguments-to-a-function "Try this code using online Editor") ``` // Defining function function showFullname(firstName, lastName) { alert(firstName + " " + lastName); } // Calling function showFullname("Clark", "Kent"); // 0utputs: Clark Kent showFullname("John"); // 0utputs: John undefined ``` *** ## Default Values for Function Parameters ES6 With ES6, now you can specify default values to the function parameters. This means that if no arguments are provided to function when it is called these default parameters values will be used. This is one of the most awaited features in JavaScript. Here's an example: #### Example [Try this code »](https://www.tutorialrepublic.com/codelab.php?topic=javascript&file=es6-function-with-default-parameter-values "Try this code using online Editor") ``` function sayHello(name = 'Guest') { alert('Hello, ' + name); } sayHello(); // 0utputs: Hello, Guest sayHello('John'); // 0utputs: Hello, John ``` While prior to ES6, to achieve the same we had to write something like this: #### Example [Try this code »](https://www.tutorialrepublic.com/codelab.php?topic=javascript&file=setting-default-values-for-function-parameters-in-older-versions "Try this code using online Editor") ``` function sayHello(name) { let name = name || 'Guest'; alert('Hello, ' + name); } sayHello(); // 0utputs: Hello, Guest sayHello('John'); // 0utputs: Hello, John ``` To learn about other ES6 features, please check out the [JavaScript ES6 features](https://www.tutorialrepublic.com/javascript-tutorial/javascript-es6-features.php) chapter. *** ## Returning Values from a Function A function can return a value back to the script that called the function as a result using the `return` statement. The value may be of any type, including arrays and objects. The `return` statement usually placed as the last line of the function before the closing curly bracket and ends it with a semicolon, as shown in the following example. #### Example [Try this code »](https://www.tutorialrepublic.com/codelab.php?topic=javascript&file=return-a-value-from-a-function "Try this code using online Editor") ``` // Defining function function getSum(num1, num2) { let total = num1 + num2; return total; } // Displaying returned value alert(getSum(6, 20)); // 0utputs: 26 alert(getSum(-5, 17)); // 0utputs: 12 ``` A function *can not* return multiple values. However, you can obtain similar results by returning an [array](https://www.tutorialrepublic.com/javascript-tutorial/javascript-arrays.php) of values, as demonstrated in the following example. #### Example [Try this code »](https://www.tutorialrepublic.com/codelab.php?topic=javascript&file=return-multiple-values-from-a-function "Try this code using online Editor") ``` // Defining function function divideNumbers(dividend, divisor){ let quotient = dividend / divisor; let arr = [dividend, divisor, quotient]; return arr; } // Store returned value in a variable let all = divideNumbers(10, 2); // Displaying individual values alert(all[0]); // 0utputs: 10 alert(all[1]); // 0utputs: 2 alert(all[2]); // 0utputs: 5 ``` *** ## Working with Function Expressions The syntax that we've used before to create functions is called function declaration. There is another syntax for creating a function that is called a function expression. #### Example [Try this code »](https://www.tutorialrepublic.com/codelab.php?topic=javascript&file=function-expression "Try this code using online Editor") ``` // Function Declaration function getSum(num1, num2) { let total = num1 + num2; return total; } // Function Expression let getSum = function(num1, num2) { let total = num1 + num2; return total; }; ``` Once function expression has been stored in a variable, the variable can be used as a function: #### Example [Try this code »](https://www.tutorialrepublic.com/codelab.php?topic=javascript&file=assign-a-function-to-a-variable "Try this code using online Editor") ``` let getSum = function(num1, num2) { let total = num1 + num2; return total; }; alert(getSum(5, 10)); // 0utputs: 15 let sum = getSum(7, 25); alert(sum); // 0utputs: 32 ``` **Note:** There is no need to put a semicolon after the closing curly bracket in a function declaration. But function expressions, on the other hand, should always end with a semicolon. **Tip:** In JavaScript functions can be stored in variables, passed into other functions as arguments, passed out of functions as return values, and constructed at run-time. The syntax of the *function declaration* and *function expression* looks very similar, but they differ in the way they are evaluated, check out the following example: #### Example [Try this code »](https://www.tutorialrepublic.com/codelab.php?topic=javascript&file=function-declaration-vs-function-expression "Try this code using online Editor") ``` declaration(); // Outputs: Hi, I'm a function declaration! function declaration() { alert("Hi, I'm a function declaration!"); } expression(); // Uncaught TypeError: undefined is not a function let expression = function() { alert("Hi, I'm a function expression!"); }; ``` As you can see in the above example, the function expression threw an exception when it was invoked before it is defined, but the function declaration executed successfully. JavaScript parse declaration function before the program executes. Therefore, it doesn't matter if the program invokes the function before it is defined because JavaScript has [hoisted the function](https://www.tutorialrepublic.com/javascript-tutorial/javascript-hoisting.php) to the top of the current scope behind the scenes. The function expression is not evaluated until it is assigned to a variable; therefore, it is still undefined when invoked. ES6 has introduced even shorter syntax for writing function expression which is called [arrow function](https://www.tutorialrepublic.com/javascript-tutorial/javascript-es6-features.php#arrow-functions), please check out the [JavaScript ES6 features](https://www.tutorialrepublic.com/javascript-tutorial/javascript-es6-features.php) chapter to learn more about it. *** ## Understanding the Variable Scope However, you can declare the variables anywhere in JavaScript. But, the location of the declaration determines the extent of a variable's availability within the JavaScript program i.e. where the variable can be used or accessed. This accessibility is known as *variable scope*. By default, variables declared within a function have *local scope* that means they cannot be viewed or manipulated from outside of that function, as shown in the example below: #### Example [Try this code »](https://www.tutorialrepublic.com/codelab.php?topic=javascript&file=local-variable "Try this code using online Editor") ``` // Defining function function greetWorld() { let greet = "Hello World!"; alert(greet); } greetWorld(); // Outputs: Hello World! alert(greet); // Uncaught ReferenceError: greet is not defined ``` However, any variables declared in a program outside of a function has *global scope* i.e. it will be available to all script, whether that script is inside a function or outside. Here's an example: #### Example [Try this code »](https://www.tutorialrepublic.com/codelab.php?topic=javascript&file=global-variable "Try this code using online Editor") ``` let greet = "Hello World!"; // Defining function function greetWorld() { alert(greet); } greetWorld(); // Outputs: Hello World! alert(greet); // Outputs: Hello World! ``` [Previous Page](https://www.tutorialrepublic.com/javascript-tutorial/javascript-loops.php) [Next Page](https://www.tutorialrepublic.com/javascript-tutorial/javascript-objects.php) Advertisements [![Bootstrap UI Design Templates](https://www.tutorialrepublic.com/lib/images/bootstrap-code-snippets.png)](https://www.tutorialrepublic.com/snippets/gallery.php) [![Property Marvels - A Leading Real Estate Portal for Premium Properties](https://www.tutorialrepublic.com/lib/images/propertymarvels.png)](https://www.propertymarvels.com/) Advertisements Is this website helpful to you? Please give us a [like](https://www.tutorialrepublic.com/like.php), or share your [feedback](https://www.tutorialrepublic.com/contact-us.php) *to help us improve*. Connect with us on [Facebook](https://www.facebook.com/tutorialrepublic) and [Twitter](https://twitter.com/tutrepublic) for the latest updates. #### About Us [Our Story](https://www.tutorialrepublic.com/about-us.php) [Terms of Use](https://www.tutorialrepublic.com/terms-of-use.php) [Privacy Policy](https://www.tutorialrepublic.com/privacy-policy.php) #### Contact [Contact Us](https://www.tutorialrepublic.com/contact-us.php) [Report Error](https://www.tutorialrepublic.com/contact-us.php) [Advertise](https://www.tutorialrepublic.com/advertise-with-us.php) #### Interactive Tools [Bootstrap Icon Search Utility](https://www.tutorialrepublic.com/bootstrap-icons-classes.php) [HTML Formatter](https://www.tutorialrepublic.com/html-formatter.php) [Title & Meta Length Calculator](https://www.tutorialrepublic.com/faq/what-is-the-maximum-length-of-title-and-meta-description-tag.php) [HTML Color Picker](https://www.tutorialrepublic.com/html-reference/html-color-picker.php) [Bootstrap Button Generator](https://www.tutorialrepublic.com/twitter-bootstrap-button-generator.php) [SQL Playground](https://www.tutorialrepublic.com/codelab.php?topic=sql&file=select-all) [Font Awesome Icon Finder](https://www.tutorialrepublic.com/font-awesome-icons-classes.php) [HTML Editor](https://www.tutorialrepublic.com/codelab.php?topic=html&file=hello-world) ![TutorialRepublic](https://www.tutorialrepublic.com/lib/images/logo.svg) [![BMC](https://www.tutorialrepublic.com/lib/images/bmc-btn.png)](https://www.buymeacoffee.com/tutrepublic) Copyright © 2026 Tutorial Republic. All Rights Reserved. *Share This:*
Readable Markdown
Advertisements In this tutorial you will learn how to define and call a function in JavaScript. ## What is Function? A function is a group of statements that perform specific tasks and can be kept and maintained separately form main program. Functions provide a way to create reusable code packages which are more portable and easier to debug. Here are some advantages of using functions: - **Functions reduces the repetition of code within a program** — Function allows you to extract commonly used block of code into a single component. Now you can perform the same task by calling this function wherever you want within your script without having to copy and paste the same block of code again and again. - **Functions makes the code much easier to maintain** — Since a function created once can be used many times, so any changes made inside a function automatically implemented at all the places without touching the several files. - **Functions makes it easier to eliminate the errors** — When the program is subdivided into functions, if any error occur you know exactly what function causing the error and where to find it. Therefore, fixing errors becomes much easier. The following section will show you how to define and call functions in your scripts. ## Defining and Calling a Function The declaration of a function start with the `function` keyword, followed by the name of the function you want to create, followed by parentheses i.e. `()` and finally place your function's code between curly brackets `{}`. Here's the basic syntax for declaring a function: function functionName() { } Here is a simple example of a function, that will show a hello message: ``` // Defining function function sayHello() { alert("Hello, welcome to this website!"); } // Calling function sayHello(); // 0utputs: Hello, welcome to this website! ``` Once a function is defined it can be called (invoked) from anywhere in the document, by typing its name followed by a set of parentheses, like `sayHello()` in the example above. **Note:** A function name must start with a letter or underscore character not with a number, optionally followed by the more letters, numbers, or underscore characters. Function names are case sensitive, just like variable names. *** ## Adding Parameters to Functions You can specify parameters when you define your function to accept input values at run time. The parameters work like placeholder variables within a function; they're replaced at run time by the values (known as argument) provided to the function at the time of invocation. Parameters are set on the first line of the function inside the set of parentheses, like this: function functionName(*parameter1*, *parameter2*, *parameter3*) { } The `displaySum()` function in the following example takes two numbers as arguments, simply add them together and then display the result in the browser. ``` // Defining function function displaySum(num1, num2) { let total = num1 + num2; alert(total); } // Calling function displaySum(6, 20); // 0utputs: 26 displaySum(-5, 17); // 0utputs: 12 ``` You can define as many parameters as you like. However for each parameter you specify, a corresponding argument needs to be passed to the function when it is called, otherwise its value becomes `undefined`. Let's consider the following example: ``` // Defining function function showFullname(firstName, lastName) { alert(firstName + " " + lastName); } // Calling function showFullname("Clark", "Kent"); // 0utputs: Clark Kent showFullname("John"); // 0utputs: John undefined ``` *** ## Default Values for Function Parameters ES6 With ES6, now you can specify default values to the function parameters. This means that if no arguments are provided to function when it is called these default parameters values will be used. This is one of the most awaited features in JavaScript. Here's an example: ``` function sayHello(name = 'Guest') { alert('Hello, ' + name); } sayHello(); // 0utputs: Hello, Guest sayHello('John'); // 0utputs: Hello, John ``` While prior to ES6, to achieve the same we had to write something like this: ``` function sayHello(name) { let name = name || 'Guest'; alert('Hello, ' + name); } sayHello(); // 0utputs: Hello, Guest sayHello('John'); // 0utputs: Hello, John ``` To learn about other ES6 features, please check out the [JavaScript ES6 features](https://www.tutorialrepublic.com/javascript-tutorial/javascript-es6-features.php) chapter. *** ## Returning Values from a Function A function can return a value back to the script that called the function as a result using the `return` statement. The value may be of any type, including arrays and objects. The `return` statement usually placed as the last line of the function before the closing curly bracket and ends it with a semicolon, as shown in the following example. ``` // Defining function function getSum(num1, num2) { let total = num1 + num2; return total; } // Displaying returned value alert(getSum(6, 20)); // 0utputs: 26 alert(getSum(-5, 17)); // 0utputs: 12 ``` A function *can not* return multiple values. However, you can obtain similar results by returning an [array](https://www.tutorialrepublic.com/javascript-tutorial/javascript-arrays.php) of values, as demonstrated in the following example. ``` // Defining function function divideNumbers(dividend, divisor){ let quotient = dividend / divisor; let arr = [dividend, divisor, quotient]; return arr; } // Store returned value in a variable let all = divideNumbers(10, 2); // Displaying individual values alert(all[0]); // 0utputs: 10 alert(all[1]); // 0utputs: 2 alert(all[2]); // 0utputs: 5 ``` *** ## Working with Function Expressions The syntax that we've used before to create functions is called function declaration. There is another syntax for creating a function that is called a function expression. ``` // Function Declaration function getSum(num1, num2) { let total = num1 + num2; return total; } // Function Expression let getSum = function(num1, num2) { let total = num1 + num2; return total; }; ``` Once function expression has been stored in a variable, the variable can be used as a function: ``` let getSum = function(num1, num2) { let total = num1 + num2; return total; }; alert(getSum(5, 10)); // 0utputs: 15 let sum = getSum(7, 25); alert(sum); // 0utputs: 32 ``` **Note:** There is no need to put a semicolon after the closing curly bracket in a function declaration. But function expressions, on the other hand, should always end with a semicolon. **Tip:** In JavaScript functions can be stored in variables, passed into other functions as arguments, passed out of functions as return values, and constructed at run-time. The syntax of the *function declaration* and *function expression* looks very similar, but they differ in the way they are evaluated, check out the following example: ``` declaration(); // Outputs: Hi, I'm a function declaration! function declaration() { alert("Hi, I'm a function declaration!"); } expression(); // Uncaught TypeError: undefined is not a function let expression = function() { alert("Hi, I'm a function expression!"); }; ``` As you can see in the above example, the function expression threw an exception when it was invoked before it is defined, but the function declaration executed successfully. JavaScript parse declaration function before the program executes. Therefore, it doesn't matter if the program invokes the function before it is defined because JavaScript has [hoisted the function](https://www.tutorialrepublic.com/javascript-tutorial/javascript-hoisting.php) to the top of the current scope behind the scenes. The function expression is not evaluated until it is assigned to a variable; therefore, it is still undefined when invoked. ES6 has introduced even shorter syntax for writing function expression which is called [arrow function](https://www.tutorialrepublic.com/javascript-tutorial/javascript-es6-features.php#arrow-functions), please check out the [JavaScript ES6 features](https://www.tutorialrepublic.com/javascript-tutorial/javascript-es6-features.php) chapter to learn more about it. *** ## Understanding the Variable Scope However, you can declare the variables anywhere in JavaScript. But, the location of the declaration determines the extent of a variable's availability within the JavaScript program i.e. where the variable can be used or accessed. This accessibility is known as *variable scope*. By default, variables declared within a function have *local scope* that means they cannot be viewed or manipulated from outside of that function, as shown in the example below: ``` // Defining function function greetWorld() { let greet = "Hello World!"; alert(greet); } greetWorld(); // Outputs: Hello World! alert(greet); // Uncaught ReferenceError: greet is not defined ``` However, any variables declared in a program outside of a function has *global scope* i.e. it will be available to all script, whether that script is inside a function or outside. Here's an example: ``` let greet = "Hello World!"; // Defining function function greetWorld() { alert(greet); } greetWorld(); // Outputs: Hello World! alert(greet); // Outputs: Hello World! ``` Advertisements
Shard147 (laksa)
Root Hash13123960086470146547
Unparsed URLcom,tutorialrepublic!www,/javascript-tutorial/javascript-functions.php s443