Function is basically used to reusable the code. A function is executed when you call it.
Syntax:-
function functionName(parameters){
// logic implement
}
Example:- Suppose you define employeeDetails function which has two parameters name and age.
function employeeDetails(name, age){
console.log("my name is "+name+" and my age is "+age);
}
How to call a function?
You have already defined the function after that you can call the function multiple times based on your requirements.
employeeDetails("John",35); //my name is John and my age is 35
employeeDetails("Rom",30); //my name is Rom and my age is 30
What is Function Scoping?
Everything defined in the function can not be access outside the function, this is called function scoping.
function user(){
var emp_name="John";
console.log(emp_name);
}
function user(){
var emp_name="John";
}
console.log(emp_name);
What is Immediately Invoke function?
When the function call itself, it is called Immediately Invoke function.
Syntax:-
(function() {
// logic
})();
Example:-
(function() {
console.log("Hello");
})();
Javascript Function – Interview Questions
Q 1: What is a function?
Ans: A block of reusable code.
Q 2: How to define a function?
Ans: function name(){}.
Q 3: Can a function return a value?
Ans: Yes.
Q 4: Can functions be nested?
Ans: Yes.
Q 5: Are functions objects?
Ans: Yes.
Javascript Function – Objective Questions (MCQs)
Q1. A function is a block of code designed to ______.
Q2. Which keyword is used to declare a function?
Q3. Function parameters are listed inside ______.
Q4. Which keyword is used to return a value from a function?
Q5. Functions in JavaScript are ______.