KEMBAR78
Lecture 4- Javascript Function presentation | PPTX
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

Lecture 4- Javascript Function presentation

  • 1.
    Attendance • Make EffectivePresentations • Using Awesome Backgrounds • Engage your Audience • Capture Audience Attention
  • 2.
  • 3.
    TOPICS FOR DISCUSSION •Introduction • Importance of functions • Creating Functions • Defining Function • User-Defined Function • Protocol • Example • Variable Scope 3
  • 4.
    Introduction • Functions andvariables 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 • AJavaScript 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 • Functionsare 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 • Thenumber 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 • Multiplearguments 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 variablenames, 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 • JavaScriptfunction 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("HelloWorld"); } 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 codeinside 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 thefollowing 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>
  • 17.
  • 18.
  • 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 • Avariable 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 • Avariable 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 GLOBALVARIABLE • 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 functionUser(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 loopis 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 doesthe 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 afor 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 loopis 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 keywordis 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.