Chapter 3

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 24

Chapter 3

Functions
Defining a function
A function definition is a regular binding where the value of the binding is a
function. For example, this code defines square to refer to a function that
produces the square of a given number:
const square = function(x) {
return x * x;
};
console.log(square(12));
// → 144
Defining a function
Function Example
Function Execution
 Merely defining a function does not result in execution of
the
function; it must be called for execution
Actual Vs formal arguments

● 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

 The value from actual argument is copied to formal


arguments
before executing the body of function
Cont.…

A function can have multiple parameters or no parameters at all. In the


following example, makeNoise does not list any parameter names, whereas
power lists two:
const makeNoise = function() {
console.log("Pling!");
};
makeNoise();
// → Pling!
Cont.…
const power = function(base, exponent) {
let result = 1;
for (let count = 0; count < exponent; count++) {
result *= base;
}
return result;
};
console.log(power(2, 10));
// → 1024
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
Bindings and scopes or Local and
Global Variables
Each binding has a scope, which is the part of the program in which the binding is
visible. For bindings defined outside of any function or block, the scope is the
whole program—you can refer to such bindings wherever you want. These are
called global.
But bindings created for function parameters or declared inside a function can be
referenced only in that function, so they are known as local bindings.
Function Hoisting
 JavaScript moves variable and function declarations to top of
the current scope; this is called hoisting
● Due to hoisting JavaScript functions can be called before they
are declared
Con…
Every time the function is called, new instances of these bindings are crea
let x = 10;
if (true) {
let y = 20;
var z = 30;
console.log(x + y + z);
// → 60
}
// y is not visible here
console.log(x + z);
// → 40ted.
Con…
Each scope can “look out” into the scope around it, so x is visible inside the block in the
example. The exception is when multiple bindings have the same name—in that case,
code can see only the innermost one. For example, when the code inside the halve
function refers to n, it is seeing its own n, not the global n.
const halve = function(n) {
return n / 2;
};
let n = 10;
console.log(halve(100));
// → 50
console.log(n);
// → 10
Nested scope
JavaScript distinguishes not just global and local bindings. Blocks and functions
can be created inside other blocks and functions, producing multiple degrees
of locality.
var name = 'Peter';
function greet() {
var greeting = 'Hello';
{
let lang = 'English';
console.log(`${lang}: ${greeting} ${name}`);
}
}
greet();
Functions as values
A function binding usually simply acts as a name for a specific piece of the program.
Such a binding is defined once and never changed. This makes it easy to confuse the
function and its name.
But the two are different. A function value can do all the things that other values can do—
you can use it in arbitrary expressions, not just call it. It is possible to store a function
value in a new binding, pass it as an argument to a function, and so on. Similarly, a
binding that holds a function is still just a regular binding and can, if not constant, be
assigned a new value, like so:

function square(x) { return x*x; }


var s = square; // Now s refers to the same function that square does
square(4); // => 16
s(4); // => 16
Declaration notation
There is a slightly shorter way to create a function binding. When the function keyword is
used at the start of a statement, it works differently.
function square(x) {
return x * x;
}
///////////
console.log("The future says:", future());
function future() {
return "You'll never have flying cars";
}
Arrow functions
There’s a third notation for functions, which looks very different from the others.
Instead of the function keyword, it uses an arrow (=>) made up of an equal sign
and a greater-than character (not to be confused with the greaterthan- or-equal
operator, which is written >=).
const power = (base, exponent) => {
let result = 1;
for (let count = 0; count < exponent; count++) {
result *= base;
}
return result;
};
When there is only one parameter name, you can omit the parentheses
around the parameter list. If the body is a single expression, rather than a
block in braces, that expression will be returned from the function. So, these two
definitions of square do the same thing:
const square1 = (x) => { return x * x; };
const square2 = x => x * x;
When an arrow function has no parameters at all, its parameter list is just
an empty set of parentheses.
const horn = () => {
console.log("Toot");
};
Optional Arguments

The following code is allowed and executes without any problem:


function square(x) { return x * x; }
console.log(square(4, true, "hedgehog"));
// → 16
Cont.…
JavaScript is extremely broad-minded about the number of arguments you pass
to a function. If you pass too many, the extra ones are ignored. If you pass too
few, the missing parameters get assigned the value undefined.
The downside of this is that it is possible—likely, even—that you’ll
accidentally pass the wrong number of arguments to functions. And no one will
tell you about it.
The upside is that this behavior can be used to allow a function to be called
with different numbers of arguments
Cont.…
For example, this minus function tries to Imi
function minus(a, b) {
if (b === undefined) return -a;
else return a - b;
}
console.log(minus(10));
// → -10
console.log(minus(10, 5));
// → 5tate the - operator by acting on either one or two arguments:
Cont.…
If you write an = operator after a parameter, followed by an expression, the value of that expression will replace the
argument when it is not given.
For example, this version of power makes its second argument optional. If you don’t provide it or pass the value
undefined, it will default to two, and the function will behave like square.
function power(base, exponent = 2) {
let result = 1;
for (let count = 0; count < exponent; count++) {
result *= base;
}
return result;
}
console.log(power(4));
// → 16
console.log(power(2, 6));
// → 64
Closure
A closure is the combination of a function and the lexical
environment within which that function was declared.
function makeAdder(x) {
return function(y) {
return x + y;
};
}
var add5 = makeAdder(5);
var add10 = makeAdder(10);
console.log(add5(2)); // 7

You might also like