What Is A Function ? A function is a block of reusable code written to perform a specific task . We can think of a function as a sub-program within the main program . . A function consists of a set of statements but executes as a single unit .
What Is A Function ? Functions are one of the fundamental concepts in programming . They let us write modular , reusable , and maintainable code
Examples Of Functions ? JavaScript provides many built-in functions such as parseInt () , parseFloat () , alert() , prompt() , confirm() etc . They all are predefined functions but now we will learn how to develop user defined functions in JavaScript .
Types Of Functions ? There are 3 popular types of functions we can develop in JavaScript : . Named Function Anonymous Function Arrow Function
Steps Needed For Function ? In JavaScript the function based programming approach requires 2 steps : Defining the function Calling the function
Syntax Of Defining A Function Functions can be defined in both <head> and <body> section but generally are placed in the head section. <script> function functionName ( arg 1,arg 2. . .) { // some code } </script>
Syntax Of Calling A Function <script> functionName ( arg 1,arg 2. . .); </script>
Points To Remember A function with no parameters must include a parenthesis after it’s name * The word “function” must be written in lowercase . *
Using arguments Array Whenever a function is invoked it gets an object called “arguments” which acts like an array and holds the arguments sent to that function . This feature is very helpful if we don’t know how many arguments might be passed to the function .
PROGRAM Write a JavaScript function called “average( )” which should accept some integers as argument and calculates and displays their sum and average .
Calling Functions Via Button A function can be called directly on a button click . For this we need to assign the function call to the onclick event attribute of the button tag. Syntax: <input type=“button” value=“some text” onclick=“ funcName (); ” >
Variable Scope Variables declared outside a function , become GLOBAL , and all scripts and functions on the web page can access it. A variable declared (using var) within a JavaScript function becomes LOCAL and can only be accessed from within that function . (the variable has local scope). If we assign a value to variable that has not yet been declared , the variable will automatically be declared as a GLOBAL variable.
Returning Values function functionName (var 1,var 2. . .) { // some code return (variable or value); } To return a value from a function we use the keyword “return” . The keyword return can only be used in a function .
A Very Important Point !! In JavaScript functions are first-class citizens . This means that we can: 1. store functions in variables 2. pass them as argument to other functions 3. return them from other functions . In simple words , we can treat functions like values .
Anonymous Functions Anonymous function is a function that does not have any name associated with it. Normally we use the function keyword before the function name to define a function in JavaScript . However, in anonymous functions in JavaScript , we use only the function keyword without the function name.
Anonymous Functions A function definition can be directly assigned to a variable . This variable is like any other variable except that it’s value is a function definition and can be used as a reference to that function . Syntax: var variablename = function(Argument List) { //Function Body };
Calling Anonymous Functions We can call an anonymous function using it’s variable name Syntax: variableName (arguments);
Some Important Built-In Functions 1. setInterval ( function_name , time_period ) Accepts the name of a function and a time period in ms and calls the function after the given ms , repeatedly . It also returns a number representing the ID value of the timer that is set which can be used with the clearInterval () method to cancel the timer 2. clearInterval ( ID ) Clears the timer ,of the given ID , set with the setInterval () method.
Some Important Built-In Functions 3. setTimeout ( function_name , time_period ) Accepts the name of a function and a time period in ms and calls the function after the given ms , only once . It also returns a number representing the ID value of the timer that is set which can be used with the clearTimeout () method to cancel the timer 4. clearTimeout ( ID ) Clears the timer ,of the given ID , set with the setTimeout () method.
var v/s let Now that we have learnt concept of functions , we must discuss the difference between var and let keywords. They differ in four ways: Scope Redeclaration Window object Using before declaring
Scope Scope essentially means where these variables are available for use . var declarations are globally scoped or function/locally scoped , while let declarations are block scoped . This means that a variable declared with var inside a function anywhere is available through out that function while a let variable declared inside a block is available only till the block terminates
Scope Example: for (var i = 1; i <= 3; i++) { console.log(i); } console.log(i); Output: 1 2 3 4 Example: for (let i = 1; i <= 3; i++) { console.log(i); } console.log(i); Output: 1 2 3 Uncaught ReferenceError : i is not defined
Redeclaration The var keyword allows us to redeclare a variable without any issue. var counter = 10; var counter = 20; console.log(counter); // 20 If we redeclare a variable with the let keyword, we will get an error : let counter = 10; let counter = 20; // error: x is already defined
The window Object We know that a variable declared globally with var becomes a property of window object but it is not true for variable declared with let . Example: var x=10; let y=20; console.log( window.x ); console.log( window.y ); Output: 10 undefined
Using Before Declaring We can use a variable created using var even before declaring it. Example: console.log(x); var x=10; console.log(x); Output: undefined 10
Using Before Declaring However , let does not allow us to do this and so if we write the previous code using let then JS will throw error : Example: console.log(x); let x=10; console.log(x); Output: Uncaught ReferenceError : Cannot access ‘x' before initialization .