Topic: Functions and Arrays
Topic: Functions and Arrays
1. FUNCTIONS
JavaScript is based on functional programming. Therefore, functions are fundamental building
blocks of JavaScript.
You define a function using 'function' keyword. The syntax for creating a function is –
function functionName(parameters) {
// SET OF STATEMENTS
}
functionName(arguments);
The function execution stops either when all the statements have been executed or a return
statement is found. The return statement stops the execution of the function and returns the
value written after the return keyword. . A function may or may not return some value after its
execution.
Function Arguments
JavaScript is a dynamic language and therefore it allows passing different number of arguments
to the function and does not give error in these condition -
● Passing fewer arguments - In this case, when few arguments are passed, the other
parameters that does not get any value assigned to them get value 'undefined' by default.
● Passing more arguments - In this case, when more arguments are passed, the extra
arguments are not considered.
function add(a, b, c) {
return a+b+c;
}
Although we will study about Objects in next session, but in context to functions you can
have access to arguments passed to function.
The argument object is used to store the arguments passed to the function in an array
like object. You can either use the parameter name or argument object to access the
values. It is helpful in cases when you don’t know the number of arguments passed to
the function.
The number of arguments can be found using - "arguments.length". The arguments can
be accessed using the brackets notation as used in arrays - "arguments[i]", where 'i' is a
number starting from 0.
Eg., the below code prints all the values of the passed to function –
function printAll() {
for(var i=0; i<arguments.length; ++i) {
console.log(arguments[i]);
}
}
In JavaScript, if you pass less arguments than in the function, the remaining parameters
defaults to 'undefined'. But you can also set your own default values to them.
Eg., the below function uses the default parameters when their values is not passed –
Eg., let’s say in a situation when we want to add at least three numbers, then we can use
something like the below function –
1.4. Hoisting
JavaScript provides a very interesting feature called as hoisting. This means that you can
use a variable or function even before it’s declaration.
NOTE: If you use a variable or function and do not declare them somewhere in the code,
then it will give an error.
You can use hoisting with both variables and function as shown below-
Variable hoisting means that you can use a variable even before it has been
declared.
The above prints 'undefined' because only the variable declaration is moved to
the top and not it’s definition.
Function hoisting means that you can use function even before function
declaration is done.
But you cannot use function hoisting when you have used function expression. If
you use function expression and use function hoisting, then it will result in an
error.
2. SCOPE
Scope of a variable is part of code where that variable is accessible. Scope of variable depends
where they are defined.
When a variable is defined globally(i.e. not in any function), it can be used anywhere in
the code. For eg.,
var i = 10;
function abc() {
console.log(i); // This will print 10
}
console.log(i); // This will print 10
2.2. Function Scope
When a variable is defined inside a function, it is accessible only within that function.
var i = 0;
function abc() {
var j = 1;
console.log(i); // This will print 0
console.log(j); // This will print 1
}
Now let’s see what happens when there are different variables with same name in
different scopes. For eg.,
var i = 0;
function abc() {
var i = 1;
console.log(i);
}
Here, within function 'abc' we have 2 variables ‘i’ i.e. one whose scope is global and
other whose scope is within function 'abc'.
Output of the above code will be 1 as preference will be given to variable that is in local
scope(here scope of function 'abc'). If we remove line 'var i = 1;', then the interpreter
will look outside the function and output will be 0.
The nested function can access the variables of the parent function and as well as the global
variables.
But the parent function cannot access the variables of the inner function.
This is useful when you want to create a variable that needs to be passed to a function. But using
a global variable is not good, as other functions can modify it. So, using nested functions will
prevent the other functions to use this variable.
Eg., using a count variable which can only be accessed and modified by the inner function -
function totalCount() {
var count = 0;
function increaseCount() {
count++;
}
increaseCount();
increaseCount();
increaseCount();
return count;
}
console.log(totalCount()); // Prints - 3
Lets now discuss, how does interpreter looks for a variable. This is decided according to
the Scope Chain -
When a variable is used inside a function, the JavaScript interpreter looks for that
variable inside the function. If the variable is not found there, then it looks for it in the
outer scope i.e. in the parent function. If it is still not found there, it will move to the
outer scope of parent and check it; and do the same until the variable is not found. The
search goes on till the global scope and if the variable is not present even in global scope
then interpreter will throw error.
Eg., the below function shows how a variable is accessed when used inside a inner
function -
function a() {
var i = 20;
function b() {
function c() {
console.log(i); // Prints - 20
}
c();
}
b();
}
a();
● Function Definition - Creating a function using function keyword and function name.
● Function Expression - Creating a function as an expression and storing it in a variable.
A function definition is creating a function in a normal way, which we have read until
now. The syntax is -
function functionName(parameters) {
// SET OF STATEMENTS
}
Here, the parameters take values differently for different types of variable. We can
either pass primitive value or non-primitive value –
● If the value passed as an argument is primitive, then it gets passed by value. This
means that the changes to the argument does not reflect the changes globally and
only remains local.
Eg.,
function abc(b) {
b = 20;
console.log(b); // Prints - 20
}
var a = 10;
abc(a);
console.log(a); // Prints - 10
We have discussed that variables can take primitive and non primitive values. So
function is one of the possible values that a variable can have. Function expression is
used to assign the function to a variable.
Eg, the below code uses the function expression with function name –
However, note that the name “fact” that this function has can be used only inside the
function to refer to itself, it can’t be used outside the function.
The function expression as shown above is named i.e. the function being assigned has a
name. We can have anonymous function expressions as well i.e. it does not has a name.
The syntax is –
Eg.,
Example,
function multiple(a, b) {
console.log(a*b);
}
function add(a, b) {
console.log(a+b);}
The function passed is also called callback function. A callback is a piece of code that is passed as
an argument to other code, which is expected to execute the argument(function) at some
convenient time.
But why do we need to use callbacks? - JavaScript is an event driven language, meaning that
instead of waiting for a response from a function, it keeps executing the code in sequence. So if
you want to execute something after some line of code, then callbacks are very useful. We will
see callbacks in upcoming sections.
6. ARRAYS
Array is an ordered collection of data(can be primitive or non-primitive), used to store multiple
values. This helps in storing indefinite number of values.
Each item/value has an 'index' attached to it, using which we can access the values. In JavaScript
'index' starts at 0.
The array also contains a property 'length' that stores the number of elements present inside the
array. It changes its value dynamically as the size of the array changes.
Another way to create an array using 'Array' object is providing the values in it like - var
arrayName = new Array(value1, value2, …, valueN). This will create an
array with these elements.
Array is heterogeneous, meaning it can contain different types of value at the same
time. Also the array can store primitive and non-primitive values.
Eg., var array = ["hammer", 85, {name: "Preeti"}, [0, 2, 6]]
You can access the individual elements of the array using the square bracket notation
like - array[1] will return '85'.
This also allows you to modify the value like - array[1] = 20 and the array now
becomes - ["hammer", 20, {name: "Preeti"}, [0, 2, 6]]
When using array inside an array, you can access the value of inner array directly like -
array[3][1] will return '2'.
If you access the array outside it’s range, i.e. you pass an invalid index(whether negative
or greater than the length of array), then 'undefined' is returned.
When you use index outside the range to add elements to an array, the array behaves in
a different manner.
When a value is assigned to positive index outside the range of array, then the array
stores this value at the specified index and all other indices before it are empty. The
length of the array also changes to 'index+1'.
When a negative value is used, then the array stores the element as a key-value pair,
where the negative index is the key and the element to be inserted is the value.
EXTRA:
You must give a read to the below links on how arrays are stored in JavaScript -
https://stackoverflow.com/questions/20321047/how-are-javascript-arrays-represented-in-
physical-memory
7. FUNCTIONS ON ARRAYS
Below are some important methods that can be used on arrays -
The 'push()' method is used to add one or more elements to the end of the array and
returns the new length of array. It uses 'length' property to add element.
If the array is empty, then 'push()' method will create 'length' property and also add
element to it.
In case, you are adding multiple elements, separate them using a comma( , ).
The 'pop()' method is used to remove the last element from the array and return that
element. It also decreases the 'length' of array by 1.
Using pop on an empty array returns 'undefined'.
The unshift()' method is used to add one or more elements to the beginning of the
array and returns the new length of array.
In case, you are adding multiple elements, separate them using a comma( , ).
The 'indexOf()' method is used to return the first index at which the given element is
found in the array. If the element is not found, then '-1' is returned.
By default the whole array is searched, but you can provide the start index from which
the search should begin. It is optional. If the index provided is negative, then the offset
is set from the end of the array and search in opposite direction is done.
You can check the examples of adding, removing and replacing from the below link -
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice#Examples
7.7. reverse Method
The 'reverse' method is used to reverse the content of the array and return the new
reversed array. This means that the first element becomes last and vice-versa.
The 'sort()' method is used to sort the elements of array and return the sorted array.
The sort is done by converting the elements to string and then comparing them.
Here, 'compareFunction(a, b)' is optional and you can provide it to sort array according
to the defined function.
You can visit the below link, to know more about 'compareFunction' -
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Description
The 'join()' method is used to concatenate all the elements in an array and return a
new string.
By default, they are separated by comma( , ), but you can also provide your own
separator as a string. It is optional to provide a separator.
The 'toString()' method is used to return the array in the form of a string. The string
contains all the elements separated by comma.
EXTRA:
You can find other methods that array uses from the below link -
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Array#Methods_2
The 'for' loop is used normally to iterate over all the values of the array.
Eg.,
var arr = [10, 20, 30];
for(var i=0; i<arr; ++i) {
console.log(arr[i]*2);
}
The 'forEach()' method calls a function once for each array element.
The syntax is -
arr.forEach(function callback(currentValue, index, array) {
/* Function Statements */
}, thisArg);
You can either provide function definition as shown in the syntax above. Or you can pass
function name to it.
Eg., the below code will print the values on the console -
var items = ['apple', 'banana', 'orange'];
items.forEach(function(item) {
console.log(item);
})
You can use the below link to find in detail about the parameters passed to the forEach
method -
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description