JavaScript Functions
ALOK SRIVASTAVA
Senior Fullstack Developer | MERN | NodeJS, ExpressJS, ReactJS, NestJS | MongoDB | GraphQL | Laravel | MySQL | AWS | Azure | GCP | Agile Scrum @LTIMindtree | Helping Jobseekers | 9K+Followers
Anonymous Function?
Function keyword is only used without the function name
<script>
var greet = function () {
console.log("Welcome to GeeksforGeeks!");
};
greet();
</script>
higher-order function.
A function that returns a function or takes other functions as arguments?
First-class Function
a function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable.
const foo = () => {
??console.log("foobar");
};
foo(); // Invoke it using the variable
// foobar
We assigned an Anonymous Function in a Variable, then we used that variable to invoke the function by adding parentheses () at the end.
function sayHello() {
??return "Hello, ";
}
function greeting(helloMessage, name) {
??console.log(helloMessage() + name);
}
// Pass `sayHello` as an argument to `greeting` function
greeting(sayHello, "JavaScript!");
// Hello, JavaScript!
We are passing our sayHello() function as an argument to the greeting() function, this explains how we are treating the function as a value.
Note: The function that we pass as an argument to another function is called a callback function. sayHello() is a callback function.
function sayHello() {
??return () => {
????console.log("Hello!");
??};
}
In this example, we are returning a function from another function - We can return a function because functions in JavaScript are treated as values.
querySelector() method returns the first element that matches a CSS selector.
To return all matches (not only the first), use the querySelectorAll() instead.
An HTMLCollection is a collection of document elements.
HTMLCollection items can be accessed by their name, id, or index number.
An HTMLCollection is always a live collection. Example: If you add a <li> element to a list in the DOM, the list in the HTMLCollection will also change.
The getElementsByClassName() and getElementsByTagName() methods return a live HTMLCollection.
A NodeList is a collection of document nodes (element nodes, attribute nodes, and text nodes).
NodeList items can only be accessed by their index number.
A NodeList is most often a static collection. Example: If you add a <li> element to a list in the DOM, the list in NodeList will not change.
The childNodes property returns a live NodeList.
The querySelectorAll() method returns a static NodeList.