Types of JavaScript Functions
JavaScript functions come in different types and have various differences, especially in ES6 (ECMAScript 2015) and later versions. Here’s a breakdown types of JavaScript functions and some ES6 features related to functions:
Function Types:
-
Named Functions:
javascriptCopy code
function add(a, b) { return a + b; }
-
Anonymous Functions:
javascriptCopy code
const add = function(a, b) { return a + b; };
-
Arrow Functions (Introduced in ES6):
javascriptCopy code
const add = (a, b) => a + b;
For Free Demo classes Call: 8237077325
Registration Link: Click Here!
Differences and Features:
-
Arrow Functions:
-
-
- Concise syntax: Arrow functions provide a shorter syntax compared to traditional function expressions.
- Lexical this: Arrow functions do not have their own this value. Instead, this is lexically bound, meaning it’s inherited from the enclosing scope.
- Cannot be constructors: Arrow functions cannot be used as constructors with the new keyword.
- No arguments binding: Arrow functions do not have their own arguments object. Instead, they inherit it from the enclosing scope.
-
-
Function Scoping:
-
-
- ES6 introduced let and const which have block scope, unlike var which has function scope. This affects how functions declared with these keywords are scoped.
-
-
Default Parameters (Introduced in ES6):
-
- You can set default values for parameters directly in the function signature.
javascriptCopy code
function greet(name = ‘World’) { console.log(`Hello, ${name}!`); } greet(); // Output: Hello, World! greet(‘John’); // Output: Hello, John!
-
Rest Parameters (Introduced in ES6):
-
- Rest parameters allow a function to accept an indefinite number of arguments as an array.
javascriptCopy code
function sum(…numbers) { return numbers.reduce((acc, curr) => acc + curr, 0); } console.log(sum(1, 2, 3, 4)); // Output: 10
-
Spread Syntax (Introduced in ES6):
-
- The spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments or elements are expected.
javascriptCopy code
const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; const combinedArray = […arr1, …arr2]; // Output: [1, 2, 3, 4, 5, 6]
-
Template Literals (Introduced in ES6):
-
- Template literals provide an easy way to interpolate variables into strings using ${} syntax.
javascriptCopy code
const name = ‘John’; console.log(`Hello, ${name}!`); // Output: Hello, John!
Must watch our video on Demand For Full Stack Developers in Future
These features introduced in ES6 enhance the capabilities and expressiveness of Advanced JavaScript functions, making them more concise and powerful.
Author:-
Sonal Vanarse
Call the Trainer and Book your free demo Class for JavaScript Call now!!!
| SevenMentor Pvt Ltd.
© Copyright 2021 | SevenMentor Pvt Ltd.