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)

Functions in javascript
Functions in javascriptFunctions in javascript
Functions in javascript
baabtra.com - No. 1 supplier of quality freshers
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
Andres Baravalle
 
Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
Computer Hardware & Trouble shooting
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
WebStackAcademy
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
CPD INDIA
 
Javascript functions
Javascript functionsJavascript functions
Javascript functions
Alaref Abushaala
 
Intro to HTML and CSS basics
Intro to HTML and CSS basicsIntro to HTML and CSS basics
Intro to HTML and CSS basics
Eliran Eliassy
 
javaScript.ppt
javaScript.pptjavaScript.ppt
javaScript.ppt
sentayehu
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
Amit Tyagi
 
Introduction to CSS
Introduction to CSSIntroduction to CSS
Introduction to CSS
Amit Tyagi
 
Css3
Css3Css3
Css3
Deepak Mangal
 
Html / CSS Presentation
Html / CSS PresentationHtml / CSS Presentation
Html / CSS Presentation
Shawn Calvert
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and Arrays
WebStackAcademy
 
CSS Basics
CSS BasicsCSS Basics
CSS Basics
WordPress Memphis
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
Varun C M
 
Span and Div tags in HTML
Span and Div tags in HTMLSpan and Div tags in HTML
Span and Div tags in HTML
Biswadip Goswami
 
cascading style sheet ppt
cascading style sheet pptcascading style sheet ppt
cascading style sheet ppt
abhilashagupta
 
Html
HtmlHtml
Html
Bhumika Ratan
 
Dom
DomDom
Dom
Rakshita Upadhyay
 
HTML CSS Basics
HTML CSS BasicsHTML CSS Basics
HTML CSS Basics
Mai Moustafa
 

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

11_Functions_Introduction.pptx javascript notes
11_Functions_Introduction.pptx javascript notes11_Functions_Introduction.pptx javascript notes
11_Functions_Introduction.pptx javascript notes
tayyabbiswas2025
 
Lecture 4- Javascript Function presentation
Lecture 4- Javascript Function presentationLecture 4- Javascript Function presentation
Lecture 4- Javascript Function presentation
GomathiUdai
 
JavaScript Introductin to Functions
JavaScript Introductin to FunctionsJavaScript Introductin to Functions
JavaScript Introductin to Functions
Charles Russell
 
java script functions, classes
java script functions, classesjava script functions, classes
java script functions, classes
Vijay Kalyan
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
JyothiAmpally
 
Java script function
Java script functionJava script function
Java script function
suresh raj sharma
 
Java script functions
Java script   functionsJava script   functions
Java script functions
chauhankapil
 
Function
FunctionFunction
Function
Saniati
 
Function Returns
Function ReturnsFunction Returns
Function Returns
primeteacher32
 
Javascript function
Javascript functionJavascript function
Javascript function
LearningTech
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
Colin DeCarlo
 
Java script
Java scriptJava script
Java script
Dhananjay Kumar
 
Object oriented java script
Object oriented java scriptObject oriented java script
Object oriented java script
vivek p s
 
The mighty js_function
The mighty js_functionThe mighty js_function
The mighty js_function
timotheeg
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
Dhruvin Shah
 
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
 
Basic Javascript
Basic JavascriptBasic Javascript
Basic Javascript
Bunlong Van
 
Functions - complex first class citizen
Functions - complex first class citizenFunctions - complex first class citizen
Functions - complex first class citizen
Vytautas Butkus
 
CS101- Introduction to Computing- Lecture 29
CS101- Introduction to Computing- Lecture 29CS101- Introduction to Computing- Lecture 29
CS101- Introduction to Computing- Lecture 29
Bilal Ahmed
 
Intro to JavaScript - Week 2: Function
Intro to JavaScript - Week 2: FunctionIntro to JavaScript - Week 2: Function
Intro to JavaScript - Week 2: Function
Jeongbae Oh
 
11_Functions_Introduction.pptx javascript notes
11_Functions_Introduction.pptx javascript notes11_Functions_Introduction.pptx javascript notes
11_Functions_Introduction.pptx javascript notes
tayyabbiswas2025
 
Lecture 4- Javascript Function presentation
Lecture 4- Javascript Function presentationLecture 4- Javascript Function presentation
Lecture 4- Javascript Function presentation
GomathiUdai
 
JavaScript Introductin to Functions
JavaScript Introductin to FunctionsJavaScript Introductin to Functions
JavaScript Introductin to Functions
Charles Russell
 
java script functions, classes
java script functions, classesjava script functions, classes
java script functions, classes
Vijay Kalyan
 
Java script functions
Java script   functionsJava script   functions
Java script functions
chauhankapil
 
Javascript function
Javascript functionJavascript function
Javascript function
LearningTech
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
Colin DeCarlo
 
Object oriented java script
Object oriented java scriptObject oriented java script
Object oriented java script
vivek p s
 
The mighty js_function
The mighty js_functionThe mighty js_function
The mighty js_function
timotheeg
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
Dhruvin Shah
 
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
 
Basic Javascript
Basic JavascriptBasic Javascript
Basic Javascript
Bunlong Van
 
Functions - complex first class citizen
Functions - complex first class citizenFunctions - complex first class citizen
Functions - complex first class citizen
Vytautas Butkus
 
CS101- Introduction to Computing- Lecture 29
CS101- Introduction to Computing- Lecture 29CS101- Introduction to Computing- Lecture 29
CS101- Introduction to Computing- Lecture 29
Bilal Ahmed
 
Intro to JavaScript - Week 2: Function
Intro to JavaScript - Week 2: FunctionIntro to JavaScript - Week 2: Function
Intro to JavaScript - Week 2: Function
Jeongbae Oh
 
Ad

More from WebStackAcademy (20)

Webstack Academy - Course Demo Webinar and Placement Journey
Webstack Academy - Course Demo Webinar and Placement JourneyWebstack Academy - Course Demo Webinar and Placement Journey
Webstack Academy - Course Demo Webinar and Placement Journey
WebStackAcademy
 
WSA: Scaling Web Service to Handle Millions of Requests per Second
WSA: Scaling Web Service to Handle Millions of Requests per SecondWSA: Scaling Web Service to Handle Millions of Requests per Second
WSA: Scaling Web Service to Handle Millions of Requests per Second
WebStackAcademy
 
WSA: Course Demo Webinar - Full Stack Developer Course
WSA: Course Demo Webinar - Full Stack Developer CourseWSA: Course Demo Webinar - Full Stack Developer Course
WSA: Course Demo Webinar - Full Stack Developer Course
WebStackAcademy
 
Career Building in AI - Technologies, Trends and Opportunities
Career Building in AI - Technologies, Trends and OpportunitiesCareer Building in AI - Technologies, Trends and Opportunities
Career Building in AI - Technologies, Trends and Opportunities
WebStackAcademy
 
Webstack Academy - Internship Kick Off
Webstack Academy - Internship Kick OffWebstack Academy - Internship Kick Off
Webstack Academy - Internship Kick Off
WebStackAcademy
 
Building Your Online Portfolio
Building Your Online PortfolioBuilding Your Online Portfolio
Building Your Online Portfolio
WebStackAcademy
 
Front-End Developer's Career Roadmap
Front-End Developer's Career RoadmapFront-End Developer's Career Roadmap
Front-End Developer's Career Roadmap
WebStackAcademy
 
Angular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and AuthorizationAngular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and Authorization
WebStackAcademy
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP Services
WebStackAcademy
 
Angular - Chapter 6 - Firebase Integration
Angular - Chapter 6 - Firebase IntegrationAngular - Chapter 6 - Firebase Integration
Angular - Chapter 6 - Firebase Integration
WebStackAcademy
 
Angular - Chapter 5 - Directives
 Angular - Chapter 5 - Directives Angular - Chapter 5 - Directives
Angular - Chapter 5 - Directives
WebStackAcademy
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - Components
WebStackAcademy
 
Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming
WebStackAcademy
 
Angular - Chapter 1 - Introduction
 Angular - Chapter 1 - Introduction Angular - Chapter 1 - Introduction
Angular - Chapter 1 - Introduction
WebStackAcademy
 
JavaScript - Chapter 14 - Form Handling
 JavaScript - Chapter 14 - Form Handling   JavaScript - Chapter 14 - Form Handling
JavaScript - Chapter 14 - Form Handling
WebStackAcademy
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
JavaScript - Chapter 1 - Problem Solving
 JavaScript - Chapter 1 - Problem Solving JavaScript - Chapter 1 - Problem Solving
JavaScript - Chapter 1 - Problem Solving
WebStackAcademy
 
jQuery - Chapter 4 - DOM Handling
jQuery - Chapter 4 - DOM Handling jQuery - Chapter 4 - DOM Handling
jQuery - Chapter 4 - DOM Handling
WebStackAcademy
 
jQuery - Chapter 5 - Ajax
jQuery - Chapter 5 -  AjaxjQuery - Chapter 5 -  Ajax
jQuery - Chapter 5 - Ajax
WebStackAcademy
 
Webstack Academy - Course Demo Webinar and Placement Journey
Webstack Academy - Course Demo Webinar and Placement JourneyWebstack Academy - Course Demo Webinar and Placement Journey
Webstack Academy - Course Demo Webinar and Placement Journey
WebStackAcademy
 
WSA: Scaling Web Service to Handle Millions of Requests per Second
WSA: Scaling Web Service to Handle Millions of Requests per SecondWSA: Scaling Web Service to Handle Millions of Requests per Second
WSA: Scaling Web Service to Handle Millions of Requests per Second
WebStackAcademy
 
WSA: Course Demo Webinar - Full Stack Developer Course
WSA: Course Demo Webinar - Full Stack Developer CourseWSA: Course Demo Webinar - Full Stack Developer Course
WSA: Course Demo Webinar - Full Stack Developer Course
WebStackAcademy
 
Career Building in AI - Technologies, Trends and Opportunities
Career Building in AI - Technologies, Trends and OpportunitiesCareer Building in AI - Technologies, Trends and Opportunities
Career Building in AI - Technologies, Trends and Opportunities
WebStackAcademy
 
Webstack Academy - Internship Kick Off
Webstack Academy - Internship Kick OffWebstack Academy - Internship Kick Off
Webstack Academy - Internship Kick Off
WebStackAcademy
 
Building Your Online Portfolio
Building Your Online PortfolioBuilding Your Online Portfolio
Building Your Online Portfolio
WebStackAcademy
 
Front-End Developer's Career Roadmap
Front-End Developer's Career RoadmapFront-End Developer's Career Roadmap
Front-End Developer's Career Roadmap
WebStackAcademy
 
Angular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and AuthorizationAngular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and Authorization
WebStackAcademy
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP Services
WebStackAcademy
 
Angular - Chapter 6 - Firebase Integration
Angular - Chapter 6 - Firebase IntegrationAngular - Chapter 6 - Firebase Integration
Angular - Chapter 6 - Firebase Integration
WebStackAcademy
 
Angular - Chapter 5 - Directives
 Angular - Chapter 5 - Directives Angular - Chapter 5 - Directives
Angular - Chapter 5 - Directives
WebStackAcademy
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - Components
WebStackAcademy
 
Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming
WebStackAcademy
 
Angular - Chapter 1 - Introduction
 Angular - Chapter 1 - Introduction Angular - Chapter 1 - Introduction
Angular - Chapter 1 - Introduction
WebStackAcademy
 
JavaScript - Chapter 14 - Form Handling
 JavaScript - Chapter 14 - Form Handling   JavaScript - Chapter 14 - Form Handling
JavaScript - Chapter 14 - Form Handling
WebStackAcademy
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
JavaScript - Chapter 1 - Problem Solving
 JavaScript - Chapter 1 - Problem Solving JavaScript - Chapter 1 - Problem Solving
JavaScript - Chapter 1 - Problem Solving
WebStackAcademy
 
jQuery - Chapter 4 - DOM Handling
jQuery - Chapter 4 - DOM Handling jQuery - Chapter 4 - DOM Handling
jQuery - Chapter 4 - DOM Handling
WebStackAcademy
 
jQuery - Chapter 5 - Ajax
jQuery - Chapter 5 -  AjaxjQuery - Chapter 5 -  Ajax
jQuery - Chapter 5 - Ajax
WebStackAcademy
 
Ad

Recently uploaded (20)

Introduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUEIntroduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUE
Google Developer Group On Campus European Universities in Egypt
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
Safe Software
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
Trends Report: Artificial Intelligence (AI)
Trends Report: Artificial Intelligence (AI)Trends Report: Artificial Intelligence (AI)
Trends Report: Artificial Intelligence (AI)
Brian Ahier
 
soulmaite review - Find Real AI soulmate review
soulmaite review - Find Real AI soulmate reviewsoulmaite review - Find Real AI soulmate review
soulmaite review - Find Real AI soulmate review
Soulmaite
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf
Minuscule Technologies
 
The case for on-premises AI
The case for on-premises AIThe case for on-premises AI
The case for on-premises AI
Principled Technologies
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Securiport - A Border Security Company
Securiport  -  A Border Security CompanySecuriport  -  A Border Security Company
Securiport - A Border Security Company
Securiport
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Co-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using ProvenanceCo-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using Provenance
Paul Groth
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Create Your First AI Agent with UiPath Agent Builder
Create Your First AI Agent with UiPath Agent BuilderCreate Your First AI Agent with UiPath Agent Builder
Create Your First AI Agent with UiPath Agent Builder
DianaGray10
 
AI Creative Generates You Passive Income Like Never Before
AI Creative Generates You Passive Income Like Never BeforeAI Creative Generates You Passive Income Like Never Before
AI Creative Generates You Passive Income Like Never Before
SivaRajan47
 
Palo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity FoundationPalo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity Foundation
VICTOR MAESTRE RAMIREZ
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
Edge AI and Vision Alliance
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Mark Zuckerberg teams up with frenemy Palmer Luckey to shape the future of XR...
Mark Zuckerberg teams up with frenemy Palmer Luckey to shape the future of XR...Mark Zuckerberg teams up with frenemy Palmer Luckey to shape the future of XR...
Mark Zuckerberg teams up with frenemy Palmer Luckey to shape the future of XR...
Scott M. Graffius
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
Safe Software
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
Trends Report: Artificial Intelligence (AI)
Trends Report: Artificial Intelligence (AI)Trends Report: Artificial Intelligence (AI)
Trends Report: Artificial Intelligence (AI)
Brian Ahier
 
soulmaite review - Find Real AI soulmate review
soulmaite review - Find Real AI soulmate reviewsoulmaite review - Find Real AI soulmate review
soulmaite review - Find Real AI soulmate review
Soulmaite
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf
Minuscule Technologies
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Securiport - A Border Security Company
Securiport  -  A Border Security CompanySecuriport  -  A Border Security Company
Securiport - A Border Security Company
Securiport
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Co-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using ProvenanceCo-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using Provenance
Paul Groth
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Create Your First AI Agent with UiPath Agent Builder
Create Your First AI Agent with UiPath Agent BuilderCreate Your First AI Agent with UiPath Agent Builder
Create Your First AI Agent with UiPath Agent Builder
DianaGray10
 
AI Creative Generates You Passive Income Like Never Before
AI Creative Generates You Passive Income Like Never BeforeAI Creative Generates You Passive Income Like Never Before
AI Creative Generates You Passive Income Like Never Before
SivaRajan47
 
Palo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity FoundationPalo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity Foundation
VICTOR MAESTRE RAMIREZ
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
Edge AI and Vision Alliance
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Mark Zuckerberg teams up with frenemy Palmer Luckey to shape the future of XR...
Mark Zuckerberg teams up with frenemy Palmer Luckey to shape the future of XR...Mark Zuckerberg teams up with frenemy Palmer Luckey to shape the future of XR...
Mark Zuckerberg teams up with frenemy Palmer Luckey to shape the future of XR...
Scott M. Graffius
 

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]