SlideShare a Scribd company logo
Attendance
• Make Effective Presentations
• Using Awesome Backgrounds
• Engage your Audience
• Capture Audience Attention
Snap Talk
TOPICS FOR DISCUSSION
• Introduction
• Importance of functions
• Creating Functions
• Defining Function
• User-Defined Function
• Protocol
• Example
• Variable Scope 3
Introduction
• Functions and variables are the key components of JavaScript.
• A function may be called once or numerous times to execute the
statements it contains.
Importance of Functions
• Define the code once, and use it many times.
• We can use the same code many times with different arguments,
to produce different results.
Unit - 1 5
Creating Functions
• A JavaScript function is a block of code designed to perform a
particular task.
• A function is a series of code statements combined together in a
single block and given a name.
• The code in the block can then be executed by referencing that
name
Defining Functions
• Functions are defined using the function keyword followed by a
name that describes the use of the function, a list of zero or more
arguments in (), and a block of one or more code statements in {}.
Syntax
function name(parameter1, parameter2, parameter3)
{
// code to be executed
}
USER DEFINED
FUNCTION
• The number of arguments passed to a function must match those
specified within the parentheses of the function block declaration.
• For example, a user-defined function requiring exactly one
argument looks like this:
function function-name ( argument-name)
{
// statements to be executed go here.
}
MULTIPLE ARGUMENTS
• Multiple arguments can be specified as a comma-separated list:
function function-name ( argument-A , argument-B, argument-C
)
{
// statements to be executed go here.
}
Protocol
• Like variable names, function names and argument names may
comprise letters, numbers, and underscore characters.
• Should not contain spaces or begin with a number
.
• Avoid the JavaScript keywords, reserved words and object names.
RETURN STATEMENT
• JavaScript function can have an optional return statement. This is
required if you want to return a value from a function. This
statement should be the last statement in a function.
• Example, you can pass two numbers in a function and then you
can expect the function to return their multiplication in your calling
program.
Function example
function myFunction(){
console.log("Hello World");
}
To execute the code in myFunction(), all you need to do is add
the following line to the main
JavaScript or inside another function.
myFunction();
Function Invocation
The code inside the function will execute when "something" invokes
(calls) the function:
• When an event occurs (when a user clicks a button)
• When it is invoked (called) from JavaScript code
• Automatically (self invoked)
Passing Variables to
Functions
• Frequently we need to pass specific values to functions that they
will be use when executing the code. Values are passed in
comma-delimited form to the function.
• The function definition needs a list of variable names in () that
match the number being passed in.
<html>
<head>
<script type="text/javascript">
function concatenate(first, last)
{ var full;
full = first + last;
return full;
}
function secondFunction()
{
var result;
result = concatenate('Zara', 'Ali');
document.write (result );
}
</script>
</head>
<body> <p>Click the following button to call the
function</p>
<form> <input type="button"
onclick="secondFunction()" value="Call Function">
</form>
<p>Use different parameters inside the function and
then try...</p> </body> </html>
Output – onclick Event
Output
RECOGNIZING VARIABLE SCOPE
• The extent to which a variable is accessible is called its “scope”
and is determined by where the variable is declared.
• It has two types
(i) local
(ii) global
LOCAL SCOPE
• A variable declared inside a function block is only accessible to
code within that same function block.
• This variable has “ local” scope it is only accessible locally within
that function, so is known as “local variable”.
GLOBAL VARIABLE
• A variable declared outside all function blocks is accessible to
code within any function block.
• This variable has “global” scope- it is accessible globally within
any function in that script so is known as a “global variable”.
LOCAL AND GLOBAL VARIABLE
• Local variables are generally preferable than global variables as
their limited scope prevents possible accidental conflicts with other
variables.
• Global variable names must be unique throughout the entire script
but local variable names only need be unique throughout their own
function block.
Using Anonymous Functions
• JavaScript also provides the ability to create anonymous functions.
• In a functional language like JavaScript, anonymous functions can
be used as parameters to functions, properties of an object, or to
return values from a function
Using Anonymous Functions
• These functions have the advantage of being defined directly in
the parameter sets when calling other functions.
For example
function doCalc(num1, num2, calcFunction)
{
return calcFunction(num1, num2);
}
Using Anonymous Functions
• define a function and then pass the function name without
parameters to doCalc(),
for example:
function addFunc(n1, n2){
return n1 + n2;
}
doCalc(5, 10, addFunc);
Using Anonymous Functions
console.log( doCalc(5, 10, function(n1, n2){ return n1 + n2; }) );
console.log( doCalc(5, 10, function(n1, n2){ return n1 * n2; }) );
• The advantage of using anonymous functions is that do not
need a formal definition,
• because it will not be used anywhere else in your code.
Using JavaScript Objects
• JavaScript has several built-in objects such as Number, Array, String, Date,
and Math.
• Each of these built-in objects has member properties and methods.
• JavaScript provides a nice object-oriented programming structure for to
create your own custom objects.
• Using objects rather than just a collection of functions is key to writing
clean, efficient, reusable JavaScript code
Using JavaScript Objects
• JavaScript has several built-in objects such as Number, Array,
String, Date, and Math.
• Each of these built-in objects has member properties and methods.
• JavaScript provides a nice object-oriented programming structure
for to create your own custom objects.
• Using objects rather than just a collection of functions is key to
writing clean, efficient, reusable JavaScript code.
Using Object Syntax
• To use objects in JavaScript effectively, need to have
an understanding of their structure and syntax.
• An object is really just a container to group multiple
values and, in some instances, functions together.
• The values of an object are called properties, and
functions are called methods.
Using Object Syntax
• To use a JavaScript object, must first create an instance of the object.
• Object instances are created using the new keyword with the object
constructor name.
• For example, to create a number object, you use the following line of
code to create an instance of the built-in Number object in
JavaScript:
var x = new Number ("5");
Using Object Syntax
• Object syntax is straightforward: use the object name, followed by
a dot, and then the property or method name.
• For example, the following lines of code get and set the name
property of an object named myObj:
• var s = myObj.name;
• myObj.name = "New Name";
Using Object Syntax
• To get and set object methods of an object in the same manner.
• For example, the following lines of code call the getName()
method and then change the method function on an object named
myObj:
• var name = myObj.getName();
• myObj.getName = function() { return this.name; };
Using Object Syntax
• To create objects and assign variables and functions directly using {} syntax.
• For example, the following code defines a new object and assigns values
and a method function:
var obj = {
name: "My Object",
value: 7,
getValue: function() { return this.value; }
};
Using Object Syntax
• To access members of a JavaScript object using the object[propertyName] syntax.
• This is useful when we are using dynamic property names or if the property name
must include characters not supported by JavaScript.
• The following examples access the "User Name" and "Other Name" properties of
an object named myObj:
var propName = "User Name";
var val1 = myObj[propName];
var val2 = myObj["Other Name"];
Creating Custom-Defined Objects
• JavaScript objects can be defined in a different ways.
• The simplest way is the on-the-fly method: To create a generic object and then
add properties to it as needed.
• For example, to create a user object and assign a first and last name as well as
define a function to return the name,
var user = new Object();
user.first="Brendan";
user.last="Dayley";
user.getName = function() { return this.first + " " + this.last; }
Creating Custom-Defined Objects
• To accomplish the same thing through direct assignment using the
following syntax where the object is enclosed in {} and the properties
are defined using property:value syntax:
var user = {
first: Brendan,
last: 'Dayley',
getName: function() { return this.first + " " + this.last; }};
Creating Custom-Defined Objects
function User(first, last){
this.first = first;
this.last = last;
this.getName = function( ) { return this.first + " " + this.last; }};
var user = new User("Brendan", "Dayley");
SUMMARY
In this session, you should have learned :
• Creating functions
• Importance of function
• Variable Scope
MCQ
1. Which loop is best suited when you know the exact number
of iterations?
a) While loop
b) For loop
c) Do/while loop
d) For/in loop
MCQ
2. What does the break keyword do in a loop?
a) Skips the current iteration
b) Stops the loop entirely
c) Starts a new loop
d) Restarts the current iteration
MCQ
3. In a for loop, where is the iteration statement usually placed?
a) Before the loop begins.
b) At the beginning of each iteration.
c) At the end of each iteration.
d) Outside the loop.
MCQ
4. Which loop is best suited for iterating over the properties of
an object?
a) for loop
b) for/in loop
c) while loop
d) do/while loop
MCQ
5. What keyword is used to exit a loop prematurely in
JavaScript?
a) Exit
b) Continue
c) Break
d) stop
Answer
1. Do/while loop;
2. Stops the loop entirely
3. At the end of each iteration
4. for/in loop
5. break
45

More Related Content

Similar to Lecture 4- Javascript Function presentation (20)

Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
Donald Sipe
 
Javascript
JavascriptJavascript
Javascript
20261A05H0SRIKAKULAS
 
Java script
 Java script Java script
Java script
bosybosy
 
Java script
Java scriptJava script
Java script
Jay Patel
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
Manvendra Singh
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
Bui Kiet
 
Rediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The LibrariesRediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The Libraries
Simon Willison
 
Basic Javascript
Basic JavascriptBasic Javascript
Basic Javascript
Bunlong Van
 
17javascript.ppt
17javascript.ppt17javascript.ppt
17javascript.ppt
bcanawakadalcollege
 
17javascript.ppt
17javascript.ppt17javascript.ppt
17javascript.ppt
PraveenRai90
 
Lecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdfLecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdf
Lê Thưởng
 
BITM3730Week6.pptx
BITM3730Week6.pptxBITM3730Week6.pptx
BITM3730Week6.pptx
MattMarino13
 
Javascript Basics by Bonny
Javascript Basics by BonnyJavascript Basics by Bonny
Javascript Basics by Bonny
Bonny Chacko
 
JavaScript and jQuery - Web Technologies (1019888BNR)
JavaScript and jQuery - Web Technologies (1019888BNR)JavaScript and jQuery - Web Technologies (1019888BNR)
JavaScript and jQuery - Web Technologies (1019888BNR)
Beat Signer
 
wp-UNIT_III.pptx
wp-UNIT_III.pptxwp-UNIT_III.pptx
wp-UNIT_III.pptx
GANDHAMKUMAR2
 
Java Script Programming on Web Application
Java Script Programming on Web ApplicationJava Script Programming on Web Application
Java Script Programming on Web Application
SripathiRavi1
 
6976.ppt
6976.ppt6976.ppt
6976.ppt
MuhammedSheriefHagra
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
JyothiAmpally
 
JavaScript with Syntax & Implementation
JavaScript with Syntax & ImplementationJavaScript with Syntax & Implementation
JavaScript with Syntax & Implementation
Soumen Santra
 
Javascript
JavascriptJavascript
Javascript
Gita Kriz
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
Donald Sipe
 
Java script
 Java script Java script
Java script
bosybosy
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
Manvendra Singh
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
Bui Kiet
 
Rediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The LibrariesRediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The Libraries
Simon Willison
 
Basic Javascript
Basic JavascriptBasic Javascript
Basic Javascript
Bunlong Van
 
Lecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdfLecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdf
Lê Thưởng
 
BITM3730Week6.pptx
BITM3730Week6.pptxBITM3730Week6.pptx
BITM3730Week6.pptx
MattMarino13
 
Javascript Basics by Bonny
Javascript Basics by BonnyJavascript Basics by Bonny
Javascript Basics by Bonny
Bonny Chacko
 
JavaScript and jQuery - Web Technologies (1019888BNR)
JavaScript and jQuery - Web Technologies (1019888BNR)JavaScript and jQuery - Web Technologies (1019888BNR)
JavaScript and jQuery - Web Technologies (1019888BNR)
Beat Signer
 
Java Script Programming on Web Application
Java Script Programming on Web ApplicationJava Script Programming on Web Application
Java Script Programming on Web Application
SripathiRavi1
 
JavaScript with Syntax & Implementation
JavaScript with Syntax & ImplementationJavaScript with Syntax & Implementation
JavaScript with Syntax & Implementation
Soumen Santra
 

Recently uploaded (20)

Strengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptxStrengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptx
SteffMusniQuiballo
 
Search Engine Optimization (SEO) for Website Success
Search Engine Optimization (SEO) for Website SuccessSearch Engine Optimization (SEO) for Website Success
Search Engine Optimization (SEO) for Website Success
Muneeb Rana
 
Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...
EduSkills OECD
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
How to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 SalesHow to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 Sales
Celine George
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptxjune 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
What are the benefits that dance brings?
What are the benefits that dance brings?What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18
Celine George
 
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
Quiz Club of PSG College of Arts & Science
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
"Hymenoptera: A Diverse and Fascinating Order".pptx
"Hymenoptera: A Diverse and Fascinating Order".pptx"Hymenoptera: A Diverse and Fascinating Order".pptx
"Hymenoptera: A Diverse and Fascinating Order".pptx
Arshad Shaikh
 
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
EduSkills OECD
 
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Celine George
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition IILDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
IDSP(INTEGRATED DISEASE SURVEILLANCE PROGRAMME...
IDSP(INTEGRATED DISEASE SURVEILLANCE PROGRAMME...IDSP(INTEGRATED DISEASE SURVEILLANCE PROGRAMME...
IDSP(INTEGRATED DISEASE SURVEILLANCE PROGRAMME...
SweetytamannaMohapat
 
Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.
jmansha170
 
POS Reporting in Odoo 18 - Odoo 18 Slides
POS Reporting in Odoo 18 - Odoo 18 SlidesPOS Reporting in Odoo 18 - Odoo 18 Slides
POS Reporting in Odoo 18 - Odoo 18 Slides
Celine George
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptxRai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Dr. Ravi Shankar Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Strengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptxStrengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptx
SteffMusniQuiballo
 
Search Engine Optimization (SEO) for Website Success
Search Engine Optimization (SEO) for Website SuccessSearch Engine Optimization (SEO) for Website Success
Search Engine Optimization (SEO) for Website Success
Muneeb Rana
 
Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...
EduSkills OECD
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
How to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 SalesHow to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 Sales
Celine George
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptxjune 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
What are the benefits that dance brings?
What are the benefits that dance brings?What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18
Celine George
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
"Hymenoptera: A Diverse and Fascinating Order".pptx
"Hymenoptera: A Diverse and Fascinating Order".pptx"Hymenoptera: A Diverse and Fascinating Order".pptx
"Hymenoptera: A Diverse and Fascinating Order".pptx
Arshad Shaikh
 
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
EduSkills OECD
 
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Celine George
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition IILDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
IDSP(INTEGRATED DISEASE SURVEILLANCE PROGRAMME...
IDSP(INTEGRATED DISEASE SURVEILLANCE PROGRAMME...IDSP(INTEGRATED DISEASE SURVEILLANCE PROGRAMME...
IDSP(INTEGRATED DISEASE SURVEILLANCE PROGRAMME...
SweetytamannaMohapat
 
Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.
jmansha170
 
POS Reporting in Odoo 18 - Odoo 18 Slides
POS Reporting in Odoo 18 - Odoo 18 SlidesPOS Reporting in Odoo 18 - Odoo 18 Slides
POS Reporting in Odoo 18 - Odoo 18 Slides
Celine George
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
Ad

Lecture 4- Javascript Function presentation

  • 1. Attendance • Make Effective Presentations • Using Awesome Backgrounds • Engage your Audience • Capture Audience Attention
  • 3. TOPICS FOR DISCUSSION • Introduction • Importance of functions • Creating Functions • Defining Function • User-Defined Function • Protocol • Example • Variable Scope 3
  • 4. Introduction • Functions and variables are the key components of JavaScript. • A function may be called once or numerous times to execute the statements it contains.
  • 5. Importance of Functions • Define the code once, and use it many times. • We can use the same code many times with different arguments, to produce different results. Unit - 1 5
  • 6. Creating Functions • A JavaScript function is a block of code designed to perform a particular task. • A function is a series of code statements combined together in a single block and given a name. • The code in the block can then be executed by referencing that name
  • 7. Defining Functions • Functions are defined using the function keyword followed by a name that describes the use of the function, a list of zero or more arguments in (), and a block of one or more code statements in {}. Syntax function name(parameter1, parameter2, parameter3) { // code to be executed }
  • 8. USER DEFINED FUNCTION • The number of arguments passed to a function must match those specified within the parentheses of the function block declaration. • For example, a user-defined function requiring exactly one argument looks like this: function function-name ( argument-name) { // statements to be executed go here. }
  • 9. MULTIPLE ARGUMENTS • Multiple arguments can be specified as a comma-separated list: function function-name ( argument-A , argument-B, argument-C ) { // statements to be executed go here. }
  • 10. Protocol • Like variable names, function names and argument names may comprise letters, numbers, and underscore characters. • Should not contain spaces or begin with a number . • Avoid the JavaScript keywords, reserved words and object names.
  • 11. RETURN STATEMENT • JavaScript function can have an optional return statement. This is required if you want to return a value from a function. This statement should be the last statement in a function. • Example, you can pass two numbers in a function and then you can expect the function to return their multiplication in your calling program.
  • 12. Function example function myFunction(){ console.log("Hello World"); } To execute the code in myFunction(), all you need to do is add the following line to the main JavaScript or inside another function. myFunction();
  • 13. Function Invocation The code inside the function will execute when "something" invokes (calls) the function: • When an event occurs (when a user clicks a button) • When it is invoked (called) from JavaScript code • Automatically (self invoked)
  • 14. Passing Variables to Functions • Frequently we need to pass specific values to functions that they will be use when executing the code. Values are passed in comma-delimited form to the function. • The function definition needs a list of variable names in () that match the number being passed in.
  • 15. <html> <head> <script type="text/javascript"> function concatenate(first, last) { var full; full = first + last; return full; } function secondFunction() { var result; result = concatenate('Zara', 'Ali'); document.write (result ); } </script> </head>
  • 16. <body> <p>Click the following button to call the function</p> <form> <input type="button" onclick="secondFunction()" value="Call Function"> </form> <p>Use different parameters inside the function and then try...</p> </body> </html>
  • 19. RECOGNIZING VARIABLE SCOPE • The extent to which a variable is accessible is called its “scope” and is determined by where the variable is declared. • It has two types (i) local (ii) global
  • 20. LOCAL SCOPE • A variable declared inside a function block is only accessible to code within that same function block. • This variable has “ local” scope it is only accessible locally within that function, so is known as “local variable”.
  • 21. GLOBAL VARIABLE • A variable declared outside all function blocks is accessible to code within any function block. • This variable has “global” scope- it is accessible globally within any function in that script so is known as a “global variable”.
  • 22. LOCAL AND GLOBAL VARIABLE • Local variables are generally preferable than global variables as their limited scope prevents possible accidental conflicts with other variables. • Global variable names must be unique throughout the entire script but local variable names only need be unique throughout their own function block.
  • 23. Using Anonymous Functions • JavaScript also provides the ability to create anonymous functions. • In a functional language like JavaScript, anonymous functions can be used as parameters to functions, properties of an object, or to return values from a function
  • 24. Using Anonymous Functions • These functions have the advantage of being defined directly in the parameter sets when calling other functions. For example function doCalc(num1, num2, calcFunction) { return calcFunction(num1, num2); }
  • 25. Using Anonymous Functions • define a function and then pass the function name without parameters to doCalc(), for example: function addFunc(n1, n2){ return n1 + n2; } doCalc(5, 10, addFunc);
  • 26. Using Anonymous Functions console.log( doCalc(5, 10, function(n1, n2){ return n1 + n2; }) ); console.log( doCalc(5, 10, function(n1, n2){ return n1 * n2; }) ); • The advantage of using anonymous functions is that do not need a formal definition, • because it will not be used anywhere else in your code.
  • 27. Using JavaScript Objects • JavaScript has several built-in objects such as Number, Array, String, Date, and Math. • Each of these built-in objects has member properties and methods. • JavaScript provides a nice object-oriented programming structure for to create your own custom objects. • Using objects rather than just a collection of functions is key to writing clean, efficient, reusable JavaScript code
  • 28. Using JavaScript Objects • JavaScript has several built-in objects such as Number, Array, String, Date, and Math. • Each of these built-in objects has member properties and methods. • JavaScript provides a nice object-oriented programming structure for to create your own custom objects. • Using objects rather than just a collection of functions is key to writing clean, efficient, reusable JavaScript code.
  • 29. Using Object Syntax • To use objects in JavaScript effectively, need to have an understanding of their structure and syntax. • An object is really just a container to group multiple values and, in some instances, functions together. • The values of an object are called properties, and functions are called methods.
  • 30. Using Object Syntax • To use a JavaScript object, must first create an instance of the object. • Object instances are created using the new keyword with the object constructor name. • For example, to create a number object, you use the following line of code to create an instance of the built-in Number object in JavaScript: var x = new Number ("5");
  • 31. Using Object Syntax • Object syntax is straightforward: use the object name, followed by a dot, and then the property or method name. • For example, the following lines of code get and set the name property of an object named myObj: • var s = myObj.name; • myObj.name = "New Name";
  • 32. Using Object Syntax • To get and set object methods of an object in the same manner. • For example, the following lines of code call the getName() method and then change the method function on an object named myObj: • var name = myObj.getName(); • myObj.getName = function() { return this.name; };
  • 33. Using Object Syntax • To create objects and assign variables and functions directly using {} syntax. • For example, the following code defines a new object and assigns values and a method function: var obj = { name: "My Object", value: 7, getValue: function() { return this.value; } };
  • 34. Using Object Syntax • To access members of a JavaScript object using the object[propertyName] syntax. • This is useful when we are using dynamic property names or if the property name must include characters not supported by JavaScript. • The following examples access the "User Name" and "Other Name" properties of an object named myObj: var propName = "User Name"; var val1 = myObj[propName]; var val2 = myObj["Other Name"];
  • 35. Creating Custom-Defined Objects • JavaScript objects can be defined in a different ways. • The simplest way is the on-the-fly method: To create a generic object and then add properties to it as needed. • For example, to create a user object and assign a first and last name as well as define a function to return the name, var user = new Object(); user.first="Brendan"; user.last="Dayley"; user.getName = function() { return this.first + " " + this.last; }
  • 36. Creating Custom-Defined Objects • To accomplish the same thing through direct assignment using the following syntax where the object is enclosed in {} and the properties are defined using property:value syntax: var user = { first: Brendan, last: 'Dayley', getName: function() { return this.first + " " + this.last; }};
  • 37. Creating Custom-Defined Objects function User(first, last){ this.first = first; this.last = last; this.getName = function( ) { return this.first + " " + this.last; }}; var user = new User("Brendan", "Dayley");
  • 38. SUMMARY In this session, you should have learned : • Creating functions • Importance of function • Variable Scope
  • 39. MCQ 1. Which loop is best suited when you know the exact number of iterations? a) While loop b) For loop c) Do/while loop d) For/in loop
  • 40. MCQ 2. What does the break keyword do in a loop? a) Skips the current iteration b) Stops the loop entirely c) Starts a new loop d) Restarts the current iteration
  • 41. MCQ 3. In a for loop, where is the iteration statement usually placed? a) Before the loop begins. b) At the beginning of each iteration. c) At the end of each iteration. d) Outside the loop.
  • 42. MCQ 4. Which loop is best suited for iterating over the properties of an object? a) for loop b) for/in loop c) while loop d) do/while loop
  • 43. MCQ 5. What keyword is used to exit a loop prematurely in JavaScript? a) Exit b) Continue c) Break d) stop
  • 44. Answer 1. Do/while loop; 2. Stops the loop entirely 3. At the end of each iteration 4. for/in loop 5. break
  • 45. 45