Introduction
Functions are the most important pillars or say building blocks of this popular scripting language called JavaScript. A function in JavaScript takes a value or set of inputs and performs its assigned task and gives us the result as output.
Definition
A function is JavaScript procedure- a set of statements that perform a task or calculate value out of it.
Defining or Declaring a Function
A function definition (also called a function declaration, or function statement) consists of the function keyword
When we define or declare a function which is also called a function declaration or function statement which consists of the function keyword followed by
- the name of the function
- parameters passed to the function
- and function is enclosed within {}
Calling a Function
Functions must be called in order to execute the function. The function doesn't automatically work after declaring it so it must be called after declaring. The calling of the functions directs the function to execute it according to the definition. The calling of the function can be done using parenthesis () just after the name of the function. Example :
function abc(){
console.log("Hello World")
}
abc()
Here in the last line abc(), the function is called.
Scope of Function
A function creates a scope so that a variable defined exclusively within the function cannot be accessed from outside the function or within other functions.
function abc() {
const a = "This is function 1"; // a can only be used by function abc
console.log("Inside function");
console.log(a);
}
console.log(a); // This cause error
const x = "This is function 2";
function xyz() {
console.log("Inside function");
console.log(x);
}
console.log(x); // The result will be -- This is function 2