SlideShare a Scribd company logo
www.webstackacademy.com ‹#›
Function
JavaScript
www.webstackacademy.com ‹#›

Introduction to functions

Passing values to functions

Returning values

Local and Global variables

Functions as objects

Function constructor
Table of Content
www.webstackacademy.com ‹#›www.webstackacademy.com ‹#›
Function basics
(JavaScript)
www.webstackacademy.com ‹#›
What is function?
●
A function is a block of JavaScript code that is defined once but
may be executed, or invoked, any number of times
●
A function can be used to return a value, construct an object, or
as a mechanism to simply run code
●
JavaScript functions are defined with the function keyword
●
Either function declaration or a function expression can be used
www.webstackacademy.com ‹#›
Function Declaration
Syntax:
function functionName (param-1, param-2, . . . , param-n) {
statement(s);
}
www.webstackacademy.com ‹#›
Parts of functions
●
Name – A unique name given by developer
●
Parameters / arguments – to pass on input values to function
●
Body – A block of statement(s) to be executed
– Local variable declaration
– Flow of computing statement(s)
– Return statement
www.webstackacademy.com ‹#›
Example :
<script>
function sum (num1, num2)
{
var result; // local variable declaration
result = num1 + num2; // computing sum
return result; // return statement
}
</script>
Function Example
Function name
return value
Formal arguments
Functionbody
Functiondefinition
www.webstackacademy.com ‹#›
<script>
. . . function definition . . .
var x = 3, y = 5, z; // global variable declaration
z = sum (x, y); // calling function for execution
document.write(“The sum of numbers is : “ + z);
</script>
Function Execution
●
Merely defining a function does not result in execution of the
function; it must be called for execution
x and y are actual arguments
www.webstackacademy.com ‹#›
<script>
. . . function definition . . .
var z = sum (4, 7); // passing literals (constants) to function
document.write(“The sum of numbers is : “ + z);
</script>
Function Execution
●
Actual arguments can be variables or literals
www.webstackacademy.com ‹#›
●
Formal arguments are the names listed within parenthesis
in function definition (also known as function parameters)
●
Formal arguments are initialized through actual arguments
at run time
●
Actual arguments are variables or literals passed to the
function at the time of invocation (call to execute)
●
The formal arguments are visible to function only
Actual Vs formal arguments
www.webstackacademy.com ‹#›
Actual Vs formal arguments
●
The value from actual argument is copied to formal arguments
before executing the body of function
3
5
3
5
x
y
Make a copy
Make a copy
num1
num2
www.webstackacademy.com ‹#›
The return statement
●
By default a function returns undefined
●
Return statement is used to return primitive value or reference of an object
●
The return value or reference
– Can be directly passed on to expressions
– Must be collected using assignment operator to store in a variable and
further utilization
●
There could be more than one return statements present in the function;
but, only one value or reference can be returned
●
The function exits after execution of return statement
www.webstackacademy.com ‹#›
Class Work
●
Write a function to find the square of a given number
●
Write a function to find sum of cubes of two numbers
●
Write a function to reverse a number
[ Hint n =12345 output : 54321 ]
●
Write a function to print all numbers between 1 and 100 which
is divisible by given number z
www.webstackacademy.com ‹#›
Local and Global Variables
●
Local variables : declared inside the function
●
Global variables: declared outside the function
●
Local variables are visible to function only and can’t be
shared across functions
●
Global variables can be shared across functions
www.webstackacademy.com ‹#›
Global Variables
<script>
var x = 3; // global variable
var y = 4; // global variable
function sum() {
return x + y;
}
</script>
●
Variables declared outside function are called global
variables
www.webstackacademy.com ‹#›
Function objects
●
JavaScript functions are objects
●
JavaScript typeof operator returns "function" for functions
www.webstackacademy.com ‹#›
Function Parameters
●
JavaScript is a weekly typed language
●
JavaScript function definitions do not specify data types
for parameters
●
JavaScript does not cross check the number of
arguments received against defined parameters
www.webstackacademy.com ‹#›
Function Parameters
<script>
. . . function definition . . .
var x = 3, y = 5, z;
z = sum (x, y, 7, 8); // No exception will be thrown here
document.write(“The sum of numbers is : “ + z);
</script>
www.webstackacademy.com ‹#›
Arguments Object
●
JavaScript functions have a built-in object called the
arguments object
●
The arguments object contains an array of the arguments
used when the function was called
●
“arguments.length” property returns number of arguments
received by function when it was invoked
www.webstackacademy.com ‹#›
Arguments Object
<script>
function addAll() {
var i, sum = 0;
for (i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}
document.write(addAll(45, 56, 64, 53, 44, 68));
</script>
www.webstackacademy.com ‹#›
Robust parameter handling
●
Function object contains length property which tells us
about defined arguments
<script>
function square (num) {
return num * num;
}
document.write(“number of formal arguments = “ + square.length);
</script>
www.webstackacademy.com ‹#›
Robust parameter handling
●
Checking passed arguments against defined
<script>
function square (num) {
if(square.length != arguments.length)
throw “square function require only one argument”;
return num * num;
}
</script>
www.webstackacademy.com ‹#›
Function Arguments
●
Primitive types are passed by value
– Value from primitive type actual argument is copied to formal
arguments
– If a function changes value through formal argument, it does not
change the original value in actual arguments
●
Objects are Passed by Reference
– In JavaScript, object references are values
– Because of this, objects will behave like they are passed by reference
– If a function changes an object property, it changes the original value
www.webstackacademy.com ‹#›
Function constructor
●
The Function constructor creates a new Function object
●
The Function() constructor expects any number of string
arguments
●
The last argument is the body of the function; JavaScript
statements are separated from each other by semicolons
●
Calling constructor directly can create functions
dynamically, but suffers from security and performance
www.webstackacademy.com ‹#›
<script>
var fullname = new Function("firstname", "lastname", “return firstname + ‘
’ + lastname;”);
document.write("Full name is " + fullname(“Tenali”, “Raman”));
</script>
Function constructor
Syntax:
var variablename = new Function(Arg1, Arg2..., "Function Body");
www.webstackacademy.com ‹#›
Web Stack Academy (P) Ltd
#83, Farah Towers,
1st floor,MG Road,
Bangalore – 560001
M: +91-80-4128 9576
T: +91-98862 69112
E: info@www.webstackacademy.com

More Related Content

What's hot (20)

PPTX
Javascript functions
Alaref Abushaala
 
PDF
3. Java Script
Jalpesh Vasa
 
PPT
JavaScript - An Introduction
Manvendra Singh
 
PPTX
JSON: The Basics
Jeff Fox
 
PPTX
Event In JavaScript
ShahDhruv21
 
PDF
Basics of JavaScript
Bala Narayanan
 
PPSX
Javascript variables and datatypes
Varun C M
 
PPTX
Lab #2: Introduction to Javascript
Walid Ashraf
 
PPTX
Javascript 101
Shlomi Komemi
 
PDF
4.2 PHP Function
Jalpesh Vasa
 
PPTX
Css selectors
Parth Trivedi
 
PPTX
Introduction to JavaScript Basics.
Hassan Ahmed Baig - Web Developer
 
PPTX
Lesson 6 php if...else...elseif statements
MLG College of Learning, Inc
 
PPTX
Java Data Types
Spotle.ai
 
PPTX
Java string handling
Salman Khan
 
PPTX
Ajax
Tech_MX
 
PPT
PHP - Introduction to Object Oriented Programming with PHP
Vibrant Technologies & Computers
 
PPTX
Arrays in java
Arzath Areeff
 
Javascript functions
Alaref Abushaala
 
3. Java Script
Jalpesh Vasa
 
JavaScript - An Introduction
Manvendra Singh
 
JSON: The Basics
Jeff Fox
 
Event In JavaScript
ShahDhruv21
 
Basics of JavaScript
Bala Narayanan
 
Javascript variables and datatypes
Varun C M
 
Lab #2: Introduction to Javascript
Walid Ashraf
 
Javascript 101
Shlomi Komemi
 
4.2 PHP Function
Jalpesh Vasa
 
Css selectors
Parth Trivedi
 
Introduction to JavaScript Basics.
Hassan Ahmed Baig - Web Developer
 
Lesson 6 php if...else...elseif statements
MLG College of Learning, Inc
 
Java Data Types
Spotle.ai
 
Java string handling
Salman Khan
 
Ajax
Tech_MX
 
PHP - Introduction to Object Oriented Programming with PHP
Vibrant Technologies & Computers
 
Arrays in java
Arzath Areeff
 

Similar to JavaScript - Chapter 6 - Basic Functions (20)

PPTX
11_Functions_Introduction.pptx javascript notes
tayyabbiswas2025
 
PPTX
Lecture 4- Javascript Function presentation
GomathiUdai
 
PPT
JavaScript Introductin to Functions
Charles Russell
 
PDF
java script functions, classes
Vijay Kalyan
 
PPT
25-functions.ppt
JyothiAmpally
 
PPTX
Java script function
suresh raj sharma
 
PPTX
Java script functions
chauhankapil
 
PPTX
Function
Saniati
 
PPTX
Function Returns
primeteacher32
 
PPTX
Javascript function
LearningTech
 
PDF
JavaScript Functions
Colin DeCarlo
 
PPTX
Java script
Dhananjay Kumar
 
PPTX
Object oriented java script
vivek p s
 
PDF
The mighty js_function
timotheeg
 
PPTX
Advanced Javascript
Dhruvin Shah
 
PDF
JavaScript and jQuery - Web Technologies (1019888BNR)
Beat Signer
 
PPT
Basic Javascript
Bunlong Van
 
PDF
Functions - complex first class citizen
Vytautas Butkus
 
PPS
CS101- Introduction to Computing- Lecture 29
Bilal Ahmed
 
PDF
Intro to JavaScript - Week 2: Function
Jeongbae Oh
 
11_Functions_Introduction.pptx javascript notes
tayyabbiswas2025
 
Lecture 4- Javascript Function presentation
GomathiUdai
 
JavaScript Introductin to Functions
Charles Russell
 
java script functions, classes
Vijay Kalyan
 
25-functions.ppt
JyothiAmpally
 
Java script function
suresh raj sharma
 
Java script functions
chauhankapil
 
Function
Saniati
 
Function Returns
primeteacher32
 
Javascript function
LearningTech
 
JavaScript Functions
Colin DeCarlo
 
Java script
Dhananjay Kumar
 
Object oriented java script
vivek p s
 
The mighty js_function
timotheeg
 
Advanced Javascript
Dhruvin Shah
 
JavaScript and jQuery - Web Technologies (1019888BNR)
Beat Signer
 
Basic Javascript
Bunlong Van
 
Functions - complex first class citizen
Vytautas Butkus
 
CS101- Introduction to Computing- Lecture 29
Bilal Ahmed
 
Intro to JavaScript - Week 2: Function
Jeongbae Oh
 
Ad

More from WebStackAcademy (20)

PDF
Webstack Academy - Course Demo Webinar and Placement Journey
WebStackAcademy
 
PDF
WSA: Scaling Web Service to Handle Millions of Requests per Second
WebStackAcademy
 
PDF
WSA: Course Demo Webinar - Full Stack Developer Course
WebStackAcademy
 
PDF
Career Building in AI - Technologies, Trends and Opportunities
WebStackAcademy
 
PDF
Webstack Academy - Internship Kick Off
WebStackAcademy
 
PDF
Building Your Online Portfolio
WebStackAcademy
 
PDF
Front-End Developer's Career Roadmap
WebStackAcademy
 
PDF
Angular - Chapter 9 - Authentication and Authorization
WebStackAcademy
 
PDF
Angular - Chapter 7 - HTTP Services
WebStackAcademy
 
PDF
Angular - Chapter 6 - Firebase Integration
WebStackAcademy
 
PDF
Angular - Chapter 5 - Directives
WebStackAcademy
 
PDF
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
PDF
Angular - Chapter 3 - Components
WebStackAcademy
 
PDF
Angular - Chapter 2 - TypeScript Programming
WebStackAcademy
 
PDF
Angular - Chapter 1 - Introduction
WebStackAcademy
 
PDF
JavaScript - Chapter 10 - Strings and Arrays
WebStackAcademy
 
PDF
JavaScript - Chapter 14 - Form Handling
WebStackAcademy
 
PDF
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
PDF
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
WebStackAcademy
 
PDF
JavaScript - Chapter 1 - Problem Solving
WebStackAcademy
 
Webstack Academy - Course Demo Webinar and Placement Journey
WebStackAcademy
 
WSA: Scaling Web Service to Handle Millions of Requests per Second
WebStackAcademy
 
WSA: Course Demo Webinar - Full Stack Developer Course
WebStackAcademy
 
Career Building in AI - Technologies, Trends and Opportunities
WebStackAcademy
 
Webstack Academy - Internship Kick Off
WebStackAcademy
 
Building Your Online Portfolio
WebStackAcademy
 
Front-End Developer's Career Roadmap
WebStackAcademy
 
Angular - Chapter 9 - Authentication and Authorization
WebStackAcademy
 
Angular - Chapter 7 - HTTP Services
WebStackAcademy
 
Angular - Chapter 6 - Firebase Integration
WebStackAcademy
 
Angular - Chapter 5 - Directives
WebStackAcademy
 
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
Angular - Chapter 3 - Components
WebStackAcademy
 
Angular - Chapter 2 - TypeScript Programming
WebStackAcademy
 
Angular - Chapter 1 - Introduction
WebStackAcademy
 
JavaScript - Chapter 10 - Strings and Arrays
WebStackAcademy
 
JavaScript - Chapter 14 - Form Handling
WebStackAcademy
 
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
WebStackAcademy
 
JavaScript - Chapter 1 - Problem Solving
WebStackAcademy
 
Ad

Recently uploaded (20)

PDF
Supporting the NextGen 911 Digital Transformation with FME
Safe Software
 
PDF
Darley - FIRST Copenhagen Lightning Talk (2025-06-26) Epochalypse 2038 - Time...
treyka
 
PDF
Optimizing the trajectory of a wheel loader working in short loading cycles
Reno Filla
 
PPTX
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
PPTX
Wondershare Filmora Crack Free Download 2025
josanj305
 
PDF
''Taming Explosive Growth: Building Resilience in a Hyper-Scaled Financial Pl...
Fwdays
 
PDF
FME as an Orchestration Tool with Principles From Data Gravity
Safe Software
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
GDG Cloud Southlake #44: Eyal Bukchin: Tightening the Kubernetes Feedback Loo...
James Anderson
 
PDF
My Journey from CAD to BIM: A True Underdog Story
Safe Software
 
PDF
5 Things to Consider When Deploying AI in Your Enterprise
Safe Software
 
PDF
Kubernetes - Architecture & Components.pdf
geethak285
 
PPTX
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
 
PDF
Why aren't you using FME Flow's CPU Time?
Safe Software
 
PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
PPTX
Smart Factory Monitoring IIoT in Machine and Production Operations.pptx
Rejig Digital
 
PDF
Bridging CAD, IBM TRIRIGA & GIS with FME: The Portland Public Schools Case
Safe Software
 
PDF
Bitkom eIDAS Summit | European Business Wallet: Use Cases, Macroeconomics, an...
Carsten Stoecker
 
PDF
Understanding The True Cost of DynamoDB Webinar
ScyllaDB
 
PDF
ArcGIS Utility Network Migration - The Hunter Water Story
Safe Software
 
Supporting the NextGen 911 Digital Transformation with FME
Safe Software
 
Darley - FIRST Copenhagen Lightning Talk (2025-06-26) Epochalypse 2038 - Time...
treyka
 
Optimizing the trajectory of a wheel loader working in short loading cycles
Reno Filla
 
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
Wondershare Filmora Crack Free Download 2025
josanj305
 
''Taming Explosive Growth: Building Resilience in a Hyper-Scaled Financial Pl...
Fwdays
 
FME as an Orchestration Tool with Principles From Data Gravity
Safe Software
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
GDG Cloud Southlake #44: Eyal Bukchin: Tightening the Kubernetes Feedback Loo...
James Anderson
 
My Journey from CAD to BIM: A True Underdog Story
Safe Software
 
5 Things to Consider When Deploying AI in Your Enterprise
Safe Software
 
Kubernetes - Architecture & Components.pdf
geethak285
 
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
 
Why aren't you using FME Flow's CPU Time?
Safe Software
 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
Smart Factory Monitoring IIoT in Machine and Production Operations.pptx
Rejig Digital
 
Bridging CAD, IBM TRIRIGA & GIS with FME: The Portland Public Schools Case
Safe Software
 
Bitkom eIDAS Summit | European Business Wallet: Use Cases, Macroeconomics, an...
Carsten Stoecker
 
Understanding The True Cost of DynamoDB Webinar
ScyllaDB
 
ArcGIS Utility Network Migration - The Hunter Water Story
Safe Software
 

JavaScript - Chapter 6 - Basic Functions

  • 2. www.webstackacademy.com ‹#›  Introduction to functions  Passing values to functions  Returning values  Local and Global variables  Functions as objects  Function constructor Table of Content
  • 4. www.webstackacademy.com ‹#› What is function? ● A function is a block of JavaScript code that is defined once but may be executed, or invoked, any number of times ● A function can be used to return a value, construct an object, or as a mechanism to simply run code ● JavaScript functions are defined with the function keyword ● Either function declaration or a function expression can be used
  • 5. www.webstackacademy.com ‹#› Function Declaration Syntax: function functionName (param-1, param-2, . . . , param-n) { statement(s); }
  • 6. www.webstackacademy.com ‹#› Parts of functions ● Name – A unique name given by developer ● Parameters / arguments – to pass on input values to function ● Body – A block of statement(s) to be executed – Local variable declaration – Flow of computing statement(s) – Return statement
  • 7. www.webstackacademy.com ‹#› Example : <script> function sum (num1, num2) { var result; // local variable declaration result = num1 + num2; // computing sum return result; // return statement } </script> Function Example Function name return value Formal arguments Functionbody Functiondefinition
  • 8. www.webstackacademy.com ‹#› <script> . . . function definition . . . var x = 3, y = 5, z; // global variable declaration z = sum (x, y); // calling function for execution document.write(“The sum of numbers is : “ + z); </script> Function Execution ● Merely defining a function does not result in execution of the function; it must be called for execution x and y are actual arguments
  • 9. www.webstackacademy.com ‹#› <script> . . . function definition . . . var z = sum (4, 7); // passing literals (constants) to function document.write(“The sum of numbers is : “ + z); </script> Function Execution ● Actual arguments can be variables or literals
  • 10. www.webstackacademy.com ‹#› ● Formal arguments are the names listed within parenthesis in function definition (also known as function parameters) ● Formal arguments are initialized through actual arguments at run time ● Actual arguments are variables or literals passed to the function at the time of invocation (call to execute) ● The formal arguments are visible to function only Actual Vs formal arguments
  • 11. www.webstackacademy.com ‹#› Actual Vs formal arguments ● The value from actual argument is copied to formal arguments before executing the body of function 3 5 3 5 x y Make a copy Make a copy num1 num2
  • 12. www.webstackacademy.com ‹#› The return statement ● By default a function returns undefined ● Return statement is used to return primitive value or reference of an object ● The return value or reference – Can be directly passed on to expressions – Must be collected using assignment operator to store in a variable and further utilization ● There could be more than one return statements present in the function; but, only one value or reference can be returned ● The function exits after execution of return statement
  • 13. www.webstackacademy.com ‹#› Class Work ● Write a function to find the square of a given number ● Write a function to find sum of cubes of two numbers ● Write a function to reverse a number [ Hint n =12345 output : 54321 ] ● Write a function to print all numbers between 1 and 100 which is divisible by given number z
  • 14. www.webstackacademy.com ‹#› Local and Global Variables ● Local variables : declared inside the function ● Global variables: declared outside the function ● Local variables are visible to function only and can’t be shared across functions ● Global variables can be shared across functions
  • 15. www.webstackacademy.com ‹#› Global Variables <script> var x = 3; // global variable var y = 4; // global variable function sum() { return x + y; } </script> ● Variables declared outside function are called global variables
  • 16. www.webstackacademy.com ‹#› Function objects ● JavaScript functions are objects ● JavaScript typeof operator returns "function" for functions
  • 17. www.webstackacademy.com ‹#› Function Parameters ● JavaScript is a weekly typed language ● JavaScript function definitions do not specify data types for parameters ● JavaScript does not cross check the number of arguments received against defined parameters
  • 18. www.webstackacademy.com ‹#› Function Parameters <script> . . . function definition . . . var x = 3, y = 5, z; z = sum (x, y, 7, 8); // No exception will be thrown here document.write(“The sum of numbers is : “ + z); </script>
  • 19. www.webstackacademy.com ‹#› Arguments Object ● JavaScript functions have a built-in object called the arguments object ● The arguments object contains an array of the arguments used when the function was called ● “arguments.length” property returns number of arguments received by function when it was invoked
  • 20. www.webstackacademy.com ‹#› Arguments Object <script> function addAll() { var i, sum = 0; for (i = 0; i < arguments.length; i++) { sum += arguments[i]; } return sum; } document.write(addAll(45, 56, 64, 53, 44, 68)); </script>
  • 21. www.webstackacademy.com ‹#› Robust parameter handling ● Function object contains length property which tells us about defined arguments <script> function square (num) { return num * num; } document.write(“number of formal arguments = “ + square.length); </script>
  • 22. www.webstackacademy.com ‹#› Robust parameter handling ● Checking passed arguments against defined <script> function square (num) { if(square.length != arguments.length) throw “square function require only one argument”; return num * num; } </script>
  • 23. www.webstackacademy.com ‹#› Function Arguments ● Primitive types are passed by value – Value from primitive type actual argument is copied to formal arguments – If a function changes value through formal argument, it does not change the original value in actual arguments ● Objects are Passed by Reference – In JavaScript, object references are values – Because of this, objects will behave like they are passed by reference – If a function changes an object property, it changes the original value
  • 24. www.webstackacademy.com ‹#› Function constructor ● The Function constructor creates a new Function object ● The Function() constructor expects any number of string arguments ● The last argument is the body of the function; JavaScript statements are separated from each other by semicolons ● Calling constructor directly can create functions dynamically, but suffers from security and performance
  • 25. www.webstackacademy.com ‹#› <script> var fullname = new Function("firstname", "lastname", “return firstname + ‘ ’ + lastname;”); document.write("Full name is " + fullname(“Tenali”, “Raman”)); </script> Function constructor Syntax: var variablename = new Function(Arg1, Arg2..., "Function Body");
  • 26. www.webstackacademy.com ‹#› Web Stack Academy (P) Ltd #83, Farah Towers, 1st floor,MG Road, Bangalore – 560001 M: +91-80-4128 9576 T: +91-98862 69112 E: [email protected]