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.

Syntax:
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.

Example:
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.
Syntax:
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).

Example:
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).
Syntax:
var nameVar = (var1, var2, ...)=>{
 //code to be executed
}
- 'var1, var2' = are function parameters (optionals).

Example:
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.
Syntax:
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:
functionName();
Example, a function that adds a string into a HTML element:
<h3 id='hid'>Default text</h3>

<script>
//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
textHid();
</script>
- 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>

<script>
//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.');
</script>
Here is an example with return:
<h3 id='sum'>Tag H3</h3>

<script>
//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;
</script>

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>

<script>
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
showVal('dv1');

//ads the current value of 'nr' in #dv2
document.getElementById('dv2').innerHTML ='The value of "nr" after the change in function is: '+nr;
</script>
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>

<script>
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
f1(5);

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

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>

<script>
//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);
}

f1(3);

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

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>

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

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

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag defines the clickable areas inside the image map?
<map> <img> <area>
<img src="image.jpg" usemap="#map1">
<map name="map1">
  <area shape="rect" coords="9, 120, 56, 149" href="#">
  <area shape="rect" coords="100, 200, 156, 249" href="#">
</map>
Which CSS property defines what is done if the content in a box is too big for its defined space?
display overflow position
#id {
  overflow: auto;
}
Click on the event which is triggered when the mouse is positioned over an object.
onclick onmouseover onmouseout
document.getElementById("id").onmouseover = function(){
  document.write("Have Good Life");
}
Indicate the PHP variable that contains data added in URL address after the "?" character.
$_SESSION $_GET $_POST
if(isset($_GET["id"])) {
  echo $_GET["id"];
}
Defining and using Functions in JS

Last accessed pages

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (137556)
  2. CSS Rhombus Shape (7522)
  3. Disable button and Enable it after specified time (17331)
  4. SHA1 Encrypt data in JavaScript (35314)
  5. How to use php variable in external js file (3709)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (245)
  2. Read Excel file data in PHP - PhpExcelReader (84)
  3. The Four Agreements (73)
  4. PHP Unzipper - Extract Zip, Rar Archives (72)
  5. The Mastery of Love (63)
Chat
Chat or leave a message for the other users
Full screenInchide