Javascript Course

Functions help organize the various parts of a script into different tasks that must be accomplished.
A function contains code that will be executed by an event or by a call to the function.
A functions can be used more than once within a script to perform its task. Rather than rewriting the entire block of code, you can simply call the function again.

There are two kinds of functions:

Defining Functions

The most basic way to define a function is using the word function, the name of the function followed by two parentheses (where we can add the parameters) and a pair of curly brackets that contain the code of the function.

function functionName(){
 alert('Love yourself; love everyone.');
The parameters var1, var2, etc. (optionals) are variables for values passed to the function. The brackets { ... } defines the start and end of the function.
- A function with no parameters must include the parentheses () after the function name.

var fun1 = function(){
 alert('Love yourself; love everyone.');

Function names are case sensitive, be sure you use the identical name when you call the function.
The word function must be written in lowercase letters.

Function assigned to variable

Another way to define a function is to assign it as value to a variable. The name of the variable will be the name of the function.
var nameVar = function(var1, var2, ...){
 //code to be executed
- 'nameVar' is the variable name, and becames the name of the function.
- 'var1, var2' = are function parameters (optionals).

var fun1 = function(){
 alert('Love yourself; love everyone.');

Arrow functions

Arrow functions are defined using a shorthand: "()=>".
- The difference is the fact that arrow-functions not have a this (that refers to the object of the function).
var nameVar = (var1, var2, ...)=>{
 //code to be executed
- 'var1, var2' = are function parameters (optionals).

var fun1 = ()=>{
 alert('Love yourself; love everyone.');

The Return Statement

A return statement is used to specific a value that a function returns when it is called. You place the return statement as the last line of the function before the closing curly bracket.
function functionName(var1, var2, ...){
 //code to be executed

 return some_var;
The next function returns the value of a variable 'z' that contain the sum of two parameters (x, y):
function amount(x, y) {
 var z = x+y;
 return z;

Calling Functions

After the function is defined, we can call and use it.
You may call a function from anywhere within a page. You can even call a function inside another function.
In the place of the script where we call a function it's executed the code of that function.

- Calling a function without paramentre has the following syntax:
Example, a function that adds a string into a HTML element:
<h3 id='hid'>Default text</h3>

//adds a HTML string in the element with id #hid
function textHid(){
 document.getElementById('hid').innerHTML ="<h3>It's always a beautiful day.</h3>";

//calling the function
- A function with parameters can be called using this syntax:
functionName(arg1, arg2, ...);
- 'arg1', 'arg2', ... are the arguments passed to the function.

Once a function is created, it can be called several times in the script.
Example, a function that adds a string into a HTML element with the id passed as argument.
<h3 id='hid1'>Tag H3</h3>
<div id='dv1'>Content Div</div>

//adds in the HTML element with the passed 'id' the string from 'str'
function addText(id, str){
 document.getElementById(id).innerHTML = str;

//calls the function two times with different values
addText('hid1', 'JavaScript Tutorial');

addText('dv1', 'Text added by calling the function.');
Here is an example with return:
<h3 id='sum'>Tag H3</h3>

//returns a string with the sum of x and y
function sumXY(x, y){
 let re = x+y;
 return 'Sum of x and y is: '+ re;

//gets the value returned by sumXY()
let sum1 = sumXY(7, 12);

//adds the value of sum1 in #sum1
document.getElementById('sum').innerHTML = sum1;

Functions and variables scope

The functions and variables defined outside a function can be used inside it.
The value of a variable defined (with var) outside a function can be changed inside it, and the change (the new value) remains outside it.

- Example, function and a variable defined outside a function, and used inside it.
<div id='dv1'>Content Div</div><br>
<div id='dv2'>Value nr</div>

var nr =8;

//doubles de value of x
function setVal(x){
 return x*2;

//adds the value returned by setVal() in the html element with passed id
//changes the value of nr variable 'nr'
function showVal(id){
 document.getElementById(id).innerHTML ='Value of "nr" doubled is: '+ setVal(nr);
 nr =99;

//calls showVal() with the id of a html element

//ads the current value of 'nr' in #dv2
document.getElementById('dv2').innerHTML ='The value of "nr" after the change in function is: '+nr;
The value of a variable created outside the function is not affected if inside function is defined (with 'let' or 'var') a variable with the same name.
<div id='dv1'>Div #dv1</div><br>
<div id='dv2'>Div #dv2</div>

var nr =8;

//define a variable 'nr' with the value of x
function f1(x){
 var nr = x;

 //adds the value of 'nr' in #dv1
 document.getElementById('dv1').innerHTML ='Value of "nr" from function: '+nr;

//calls f1() with a value for nr

//adds the value of 'nr' in #dv2. external 'nr' isn't modified
document.getElementById('dv2').innerHTML ='Value of external "nr" is: '+nr;

Nested Functions

Inside a function you can define and call another function.
The functions and variables created inside a function cannot be used outside it.

- Example, using nested function.
<div id='dv1'>Content HTML</div>

//in this function is created and used an 'arrow function'
function f1(x){
 //nested arrow function
 let f2 =(x)=>{
 return 'X doubled is: '+ (x*2);

 //if x < 4 adds in #dv1 the result returned by f2()
 if(x <4) document.getElementById('dv1').innerHTML = f2(x);


//trying to call f2(), shows error in browser console
f2(3); //ReferenceError: f2 is not defined

Anonymous Functions

Anonymous functions do not have a name, they can not be called, they are created directly as an argument passed to another function.
Anonymous functions can be defined with the 'function' keyword, or like 'arrow functions'.
- Example, the JavaScript's setTimeout() function requires two arguments, the first is a function, the second is a numeric value (milliseconds).
<div id='dv1'>Div #dv1</div><br>
<div id='dv2'>Div #dv2</div>

//the first argument is an anonymous function, that will be executed by setTimeout() after 2 seconds
 document.getElementById('dv1').innerHTML ='<h3>Life is Happiness; Be Happy.</h3>';

//the first argument is an anonymous arrow function, executed by setTimeout() after 3 seconds
 document.getElementById('dv2').innerHTML ='<h3>Every day is a wonderful day; Be Happy.</h3>';

Daily Test with Code Example

Which tag can be used to create input text field in web page?
<form> <input> <div>
<input type="text" name="a_name" value="val" />
Which CSS property displays the text in a small-caps font?
display font-variant font-style
h3 {
  font-variant: small-caps;
What instruction displays a notice box with a message inside it, in JavaScript?
for() Date() alert()
var msg = "Visit";
Indicate the PHP code used to get the users IP.
echo $ip;
Defining and using Functions in JS

Last accessed pages

  1. PHP-MySQL free course, online tutorials PHP MySQL code (67646)
  2. Clear Canvas Context (7716)
  3. PHP Predefined Constants (580)
  4. PhpSpreadsheet - Read, Write Excel and LibreOffice Calc files (24918)
  5. PHP Code Snippets (7749)

Popular pages this month

  1. PHP Unzipper - Extract Zip, Rar Archives (807)
  2. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (565)
  3. SHA1 Encrypt data in JavaScript (433)
  4. Create simple Website with PHP (398)
  5. Read Excel file data in PHP - PhpExcelReader (392)