Functions
- What is a function?
- Pre-defined functions
- Scope of Variables
- Function Expressions
- Anonymous Functions
- Callback Functions
Objects
- What is an object?
- Accessing Object Properties
- Calling an Object’s Methods
- Altering Properties/Methods
Array Properties and Methods
- The length property
- Stack Methods
- Queue Methods
- Reordering Methods
- Manipulation Methods
- Location Methods
- Iterative Methods
- Working with array of objects
DOM
- The Document Object Model
- Node Relationships
- Working with the Contents of Elements
- Getting Elements by ID, Tag Name, or Class
- Adding and removing element
Built-in Objects
Using Events in JavaScript
Handling Input and Output
Ajax and JSON
Functions allow you to group together some code, give this code a name, and reuse it later, addressing it by name. A function is a block of code that can be reused to avoid repetition of code.
Let’s take the example of a TV remote. The buttons in a TV remote control have their own functionality. When we click on ‘MUTE’ button, mute function will be executed on the TV. In the same way volume function, changing channel function will be executed in the TV.
What are the parts that make up a function?
- The function statement.
- The name of the function, in this case sum.
- Expected parameters.
- A code block, also called the body of the function.
- The return statement. A function always returns a value. If it doesn’t return value explicitly, it implicitly returns the value undefined.
Now, let’s understand a simple example:
function printHi(){
console.log("hi");
}
This is a simple function that prints “hi” in the console. It executes the lines present inside it. But it will only execute the code when we “call” the function. In order to “call” the above function, we need to write as follows:
printHi();
But the capability of a function is not only to execute certain lines of code. It can also “return” a value. This means that a function can give us a value back which we can store and reuse it elsewhere. Let us consider a function as follows:
function add(){
var x = 10;
var y = 20;
x + y;
}
var sum = add();
If we try to print the value of sum(using console.log(sum)), we will see that it prints “undefined”. This is because our function is returning nothing. A return statement is required to return a value. Without the return statement, the function returns nothing and so nothing is assigned to sum. Hence, sum gives undefined.
If we want to return some value, we need to use the “return” keyword inside the function. For example:
function add(){
var x = 10;
var y = 20;
return (x + y);
}
var sum = add();
console.log(sum);
This will print 30 in the console because x + y is being returned by the add function. We can say that the function is returning an integer value i.e. 30.
The “return” keyword not only returns or gives a value back to us but also ends or stops the function execution. Any lines of code after the return statement will not be executed.
For example:
function add(){
var x = 10;
var y = 20;
return(x + y);
console.log("hi");
}
var sum = add();
console.log(sum);
The above code will print the number 30 but it will not print “hi” because the return statement ends the function execution at that point and any line after the return statement is not executed.
If we simply want to end the function execution, we can use an empty return statement as follows:
function squareOfEven(n){
if(n%2!==0){
console.log("error");
return;
}
console.log(n*n);
}
Here, the function first checks if the given number is odd. If it is odd, it simply ends the function execution by using an empty return statement which returns undefined. If it is even, it will print the square of the number.
So, we can say that,
- If there is no return statement, a function returns nothing.
- If there is a return statement with some value, it returns the value and ends the function execution.
- If there is an empty return statement, it returns undefined and ends the function execution.
Till now, we have seen several functions written in different ways. In the last example, the function squareOfEven was taking a value, ‘n’ within parentheses. This ‘n’ is known as a parameter of the function. A function can have zero or more parameters in its definition. If a function has one or more parameters in its definition, we need to pass a value for each parameter while calling the function. The values that we pass while we call the function are known as arguments. For example, while calling the function squareOfEven, we need to pass an argument as follows:
squareOfEven(8);
Here, 8 is the argument we are passing that the function accepts to calculate the square. So, we can say that:
- ‘n’ is the parameter for the function definition
- ‘8’ is the argument that we pass while calling the function
When defining a function, you can specify what parameters the function expects to receive when it is called. A function may not require any parameters, but if it does and you forget to pass them, JavaScript will assign the value undefined to the ones you skipped.
In the next example, the function call returns NaN because it tries to sum 1 and undefined:
function sum(a,b){
return (a + b);
}
sum(1)
//NaN
JavaScript is not picky at all when it comes to parameters. If you pass more parameters than the function expects, the extra parameters will be silently ignored:
sum(1, 2, 3, 4, 5)
//3
Examples
Create a function to subtract two numbers and return the value.
For subtracting, we need a function that takes two arguments.
function subtract(a,b) {
var c = a - b;
return c;
}
Create a function to return the square of a number.
function square(a) {
return a*a;
}
Create a function to return the remainder of division of a number by another number.
function remainder(a,b) {
var c = a % b;
return c;
}
Create a function to print “Hello World” in the console.
function print() {
console.log('Hello World');
}
Create a function to check whether a number is even or odd.
Here, we need to use if else to check whether the number is even or odd as follows:
function evenodd(x) {
if(x%2===0){
console.log('It is even');
}
else{
console.log('It is odd');
}
Create a function to print all the prime numbers between 1 and 10 in descending order.
function prime() {
for(var i=1;i<=10;i++) {
var count = 0;
for(var j=1;j<=i;j++) {
if(i%j===0) {
count++;
}
}
if(count===2) {
console.log(i);
}
}
Quiz
Click on this link for MCQs on JavaScript functions: Function quiz questions
Assignments
- Write a function which can add two numbers
- Write a function which can display the greatest of the three numbers passed in arguments.
- Write a function which can display the given arguments in ascending order
- Write a function which can display the factorial of a number
- Write a function which can to display the reverse of a given number
- Write a function which can check a given number is palindrome or not
- Write a function which can check a given number is prime number or not
- Write a function which can check a given number is Armstrong number or not
- Write a function which can return the factorial of a number to another variable
- Write a function to display the number of digits in the given number
- Write a function that returns an array of all even numbers between 1 and 20.