Home Web Front-end JS Tutorial All About JavaScript Function

All About JavaScript Function

Sep 12, 2024 pm 10:32 PM

What Will We Learn?

  1. What Is Function
  2. Terminologies
  3. Different Types of Functions
  4. Function Declarations
  5. Function Executions
  6. Parameter
  7. Call Stack
  8. Nested Functions
  9. Functions Scope
  10. Closure
  11. Callback Function
  12. Higher Order Function
  13. Pure Function
  14. IIFE
  15. Recursion

?? What is javascript function?

A

function is a code block that is used to perform a specific task. A function, once defined, can be used repeatedly. This reduces code repetition.


?? Function Terminologies:

? Defining functions:

a. Function Declarations:

When a function is created using the keyword-function, a name of the function, one or more parameters and a statement, it is called a function declaration. function declaration, also known as function statement.

The

statement is the {// do this task} code block inside the function. The desired result from the function is sent to the function called/invoked via return.

All About JavaScript Function

function functionName (parameter1, parameter2) {
    return parameter1 + parameter2;
}

functionName(4, 2); // Output: 6
Copy after login

function name can be anything. But while calling/invoking the function, you have to use exactly function name. () or parentheses must be used at the end of the name.

function parameters is the variable in parentheses after the function name. Multiple parameters require commas (,) between parameters.

parameters arguments receive value **does.

The result expected from the

function is passed to the function call via the return keyword. return results in the completion of the function. That is, after return the function does not execute any more code.

function call/invoke The value that is passed inside ()- is called arguments.

b. Function Expression:

Declaring a function without a function name is called a function expression. Function Expression, also known as anonymous function.

const functionExpressionfunction = function (num) {
    return num +1;
}

functionExpressionfunction(5); // Output: 6
Copy after login

NB: Although there is a fundamental difference between Function Declaration and Function Definition, in the general sense it means to create a function.


?? Function VS Method (difference between function and method):

a. Functions:

Function is an independent code block that can perform specific tasks. The output is obtained from the input by calling the function from anywhere in the code.

function greet(name) {
    return `Hello, ${name}!`;
}

console.log(greet("Rabiul")); // Output: Hello, Rabiul!
Copy after login

b. Methods:

Method is also a function but it refers to object, used as a property of object. That is, Method will always be used as a property of object.

const user = {
    firstName: "Khan",
    middleName: "Rabiul",
    lastName: "Islam",
    fullName : function () {
        return `${this.firstName} ${this.middleName} ${this.lastName}` 
    }
}
console.log(user.fullName());
Copy after login

?‍? Parameter:

? a. Default Parameter:

JavaScript Function, parameterএর value undefinedথাকে। undefined ভেলুর সাথে অপরেশন করা সম্ভব নয়। আবার কিছু ক্ষেত্রে প্যারামিটারের ভ্যেলু সেট করার প্রয়োজন হতে পারে। সে সব ক্ষেত্রে default parameter ব্যবহার করা যায়।

function multiple (num1, num2 =1) {
    return num1 * num2;
}

multiple(5); // Output: 5 * 1 = 5
multiple(5, 2); // Output: 5 * 2 = 10
Copy after login

Parameters এর নির্দিষ্ট value (=value) ব্যবহার করে যতগুলো default parameter প্রয়োজন ততোগুলো ব্যবহার করা যায়।

? b. Rest Parameter:

JavaScript rest parameter অসংখ্য argument কে array আকারে receive করে। rest parameter মূলত (…নাম) দ্বারা গঠিত।

function sum (num1, num2, ...rest) {
    const restSum = rest.reduce((total, num) => total + num, 0)
    return num1 + num2 + restSum;
}
sum(4,5,6,7,8,10,12);
Copy after login

All About JavaScript Function

Rest parameter এর কিছু গুরুত্বপূর্ণ বিষয়ঃ

পূর্বে আমারা Function Declaration ও Function Expression নিয়ে আলোচনা করেছি। এখানে শুধু Arrow Function নিয়ে আলোচনা করা হবে।

  • একটি functionএ একটিমাত্র rest প্যারামিটার থাকতে পারবে।
  • rest প্যারামিটার সব parameterএর শেষে হবে।
  • rest প্যারামিটার এর কোন default value থাকতে পারবে না।

?‍? বিভিন্ন প্রকারের Functions:

পূর্বে আমারা Function Declaration ও Function Expression নিয়ে আলোচনা করেছি। এখানে শুধু Arrow Function নিয়ে আলোচনা করা হবে।

? Arrow Function:

Function কে সংক্ষিপ্ত আকারে লেখার জন্য arrow function ব্যবহার করা হয়।

Syntax:

() => expression

param => expression

(param) => expression

(param1, parameter2) => expression

() => {
  statements
}

param => {
  statements
}

(param1, paramN) => {
  statements
}

Copy after login

উদাহরণঃ

const sum = (a, b) => {
    return a + b;
};

console.log(sum(5, 10)); // আউটপুট: 15

Copy after login
const sum = (a, b) => a + b;

console.log(sum(5, 10)); // আউটপুট: 15

Copy after login
const square = x => x * x;

console.log(square(5)); // আউটপুট: 25

Copy after login

একটি parameter এর জন্য (), ব্যবহার প্রয়জন নেই। আবার একটি expression এর জন্য, {} এবং return keyword ব্যবহার জরুরি নয়।


?‍? Nested Function:

একটি function-কে যখন অন্য একটি function এর মধ্যে define করা হয়, তখন তাকে Nested Function বলে।

 function outerFunction () {
    console.log('outer funciton');
    function inner () {
        console.log('Inner function');
    }
    inner();
 }

console.log( outerFunction());  
// Output: outer funciton
// Inner function
Copy after login

প্রয়োজনে আমারা একাধিক nested function ব্যবহার করতে পারি।


?‍? Function Scope:

function scope এমন একটি ধারণা যেখানে function এর ভিতরের variable গুলোর ব্যবহার ও access ঐ function এর মধ্যেই সীমাবদ্ধ। অর্থাৎ function এর বাইরে variable গুলোর access পাওয়া যাবেনা।

function outerFunction() {
    const a = 10;
    function innerFunction() {
        const b = 5;
        console.log(a); // Logs '10'
        function corefunction() {
            console.log(a); // Logs '10'
            console.log(b); // Logs '5'
            const c = 2;
            return a + b + c; // Returns 10 + 5 + 2 = 17
        }
        return corefunction;
    }
    return innerFunction;
}

const inner = outerFunction(); // Returns innerFunction
const core = inner();          // Returns corefunction
console.log(core());          // Logs '10', '5', and '17'


console.log(a);
console.log(b);
console.log(c);

// Output: Uncaught ReferenceError: b is not defined

Copy after login

function এর বাইরে variable access করতে গেলে ReferenceErro; দেখাচ্ছে কেননা variable, function এর ভিতর define করা হয়েছে।

All About JavaScript Function


?‍? Closures:

কয়েকটি functionএর সমন্বয়ে গঠিত Lexical Environment, যা নির্ধারণ করে একটি functionএর মধ্যে variableঅন্য functionগুলো access/ব্যবহার পাবে কি না। অর্থাৎ, যখন একটি functionঅন্য functionএর ভিতর গঠিত হয়, তখন ভিতরের functionতার বাইরের functionএর variable মনে রাখতে পারে এবং access/ব্যবহার করতে পারে। এধারনাকে ক্লোজার(closure) বলে।

function outerFunction () {
    const outerVariable = 'This is outer variable value';
    function innerFunction () {
        console.log(outerVariable);
    }
    return innerFunction;
}

const closuer = outerFunction();
closuer();
// Output: This is outer variable value
Copy after login

পাশের কোড স্নিপিটে outerFunction এর ভিতর outerVariable নামে একটি variable init এবং assign করা হয়েছে। একই সাথে innerFunction নামে একটি function declare করে হয়েছে। আবার innerFunction কে console.log()/access করা হয়েছে। যেহেতু Lexical Enviornment এ inner function তার বাইরের function এর variable মনে রাখতে পারে, তাই যখন outerFunction কে call করা হলো তখন innerFunction তার outer function থেকে variable এর value গ্রহন করতে পেরেছে।

function outerFunction () {
    const a = 10;
    function innerFunction () {
        const b = 5;
        function hardCoreFunction () {
            const c = 20;
            return a + b + c;
        }
        return hardCoreFunction()
    }
    return innerFunction;
}
const closure = outerFunction();
console.log(closure())
Copy after login

উদাহরণ ২ঃ outerFunction Lexical Scope এর ভিতর আরো ২টি function declare করা হয়েছে innerFunction এবং hardCoreFunction। outerFunction function এর ভিতর a = 10 innerFunction এ b = 5 এবং hardCoreFunction এর ভিতর c = 20 এবং variable a, b, c variable এর সমষ্টি নির্ণয় করা হয়েছে। hardCoreFunction এর ভিতর variable a এবং b না থাকার পরও lexical enviornment এর কারোনে access করতে পারছে।

function outerFunction () {
    const a = 10;
    function innerFunction () {
        const b = 5;
        console.log(a);
        console.log(c);
        function hardCoreFunction () {
            const c = 20;
            return a + b + c;
        }
        return hardCoreFunction()
    }
    return innerFunction;
}
const closure = outerFunction();
console.log(closure())
Copy after login

All About JavaScript Function

উধাহরণ ৩ঃ innerFunction এর ভিতর variable a এবং c বিদ্যমান নয়। a ও c access করতে গেলে a এর value পাওয়া output পাওয়া গেলেও c variable এর access না থাকায়, Output REferenceError show করছে। বুঝারা সুবিধার্তে outerFunction কে grand_parent, innerFunction কে parent এবং hardCoreFunction child হিসেবে বিবেচনা করা হলো। child তার parent, grand_parent variable access পাই। এমনকি child সরাসরি grand_parent কেও access করতে পারবে। কিন্তু কোনো parent তার child এর variable access করতে পারবে না।

All About JavaScript Function

সহজভাবে বলতে গেলে ক্লোজার(closure) হলো যখন inner function তার Lexical Environment এ outer function থেকে variable access করে।


?‍? Callbac Function:

Arguments আকারে একটি function কে অন্য একটি function এ pass করে, কোন কার্যসম্পাদনকে callback function বলে। callback function কে function এর মধ্যে invoked/call করেতে হয়।

synchronous এবং asynchronous ২ পদ্ধতিতে callback function ব্যবহার করা যায়।

function multiplyByTwo(num, callbackFunc) {
    var result = num * 2;
    callbackFunc(result);
  }

  function ConLogResult(result) {
    console.log(result);
  }

  multiplyByTwo(5, ConLogResult);
Copy after login

All About JavaScript Function


?‍? Higher Order Function:

একটি function, এক বা একাধিক function arguments থেকে গ্রহণ করে অথবা ফলাফল হিসেবে function কে return করে, তাকে Higher Order Function (HoF) বলে।

? Higher Order Function এর ২টি বৈশিষ্ট্যঃ

  1. Argument এ function গ্রহণ করে।

  2. ফলাফল হিসেবে function প্রদান করে।

1. Argument এ function গ্রহণ করে:

function higherOrderFunction (callbackFun) {
    callbackFun('It is a higher Order Function');
}

function callbackFun (message) {
    console.log(message)
}

higherOrderFunction(callbackFun);

Copy after login

All About JavaScript Function

এখানে higherOrderFunction, call করার সময় argument এ অন্য একটি function pass করছে।

কোথায় Higher Order Function ব্যবহার করা হয়ঃ

const radius = [4,5,8];

// Calculating Area of the circle
const circleArea = function (radius) {
    const result = []; // initialized arra to store output
    for(let i = 0; i < radius.length; i++) {
        result.push(Math.PI * (radius[i], radius[i]));
    }
    return result;
}

console.log(circleArea(radius));
// Output: [12.566370614359172, 15.707963267948966, 25.132741228718345]


const diameter = function (radius) {
    const result = [];
    for (let i = 0; i<radius.length; i++) {
        result.push(2 * radius[i]);
    }
    return result;
}
console.log(diameter(radius));
// Output: [8, 10, 16]
Copy after login

উভয় ক্ষেত্রে দেখা যাচ্ছে radius variable কে access করছে। কিন্তু function এর operation গুলো ভিন্ন। এমন ক্ষেত্রে ভিন্ন operation এর জন্য ভিন্ন function তৈরী করে, অন্য একটি function এর argument এ pass করে একটি পুনঃ ব্যবহারযোগ্য function/higher order function গঠন করতে পারি।

const radius = [4,5,8];

// Calculating diameter
const diameter = function (radius) {
    const result = [];
    for (let i = 0; i<radius.length; i++) {
        result.push(2 * radius[i]);
    }
    return result;
}
console.log(diameter(radius));


// Area clcultion's Operation 
const area = function (radius) {
    return Math.PI * radius * radius;
}
// Diameter clcultion's Operation 
const diameter = function (radius) {
    return 2 * radius;
}

// Making a function that can calculate area, diameter, and other oprations. It will be a resuable function

const calculate = function (radius, operation) {
    const output = [];
    for(i = 0; 0 < radius.length; i++) {
        output.push(operation[i]);
    }
    return output;
}

console.log(calculate(radius,diameter));
console.log(calculate(radius,area));
Copy after login

All About JavaScript Function

ধাপ ১ঃ একটি function তৈরী করি, যেটি একটি value এবং একটি function রিসিভ করতে পারবে।

ধাপ ২ঃ প্রত্যেকটি আলাদা operation এর জন্য ভিন্ন ভিন্ন function define করি।

ধাপ ৩ঃ HoFs কে call করার সময় প্রয়োজনীয় operation/function কে pass করি। এখানে value = radius এবং function/operaton = diameter/area;

ধাপ ৪ঃ callback function কে function টির ভিতর call করি। argument এ প্রয়োজনীয় value pass করি।

এখন function/operation টি অটোমেটিক প্রাপ্ত value থেকে operation সম্পন্ন করে HoFs এর যেখানে call করা হয়েছে, সেখানে প্রদান করবে।

? ২. ফলাফল হিসেবে function প্রদান করে(return a function):

Higher Order Function ফলাফল হিসেবে অন্য একটি function এর return ফল গ্রহণ করতে পারে।

function higherOrderFunction (a, b) {
     function sum (b) {
        return a + b;
    }
    return sum;
}
console.log( higherOrderFunction(4)(5));
// Output: 9


// Or

function higherOrderFunction (a, b) {
    return function sum (b) {
       return a + b;
   }
}
console.log( higherOrderFunction(4)(5));
// Output: 9
Copy after login

ব্যবহারঃ

  1. Array: map(), reduce(), filter(), sort()...
  2. Object: Object.entries()
  3. Custom

উদাহরণ ১ঃ

একটি array এর প্রতিটি number element কে ২ দ্বারা গুণ করতে হবে।

const users = [
    {firstName: 'Khan', lastName: 'Rabiul', age: 30},
    {firstName: 'Anisul', lastName: 'Islam', age: 20},
    {firstName: 'Shahidul', lastName: 'Islam', age: 25},
    {firstName: 'Mr.', lastName: 'Sabbir', age: 32},
    {firstName: 'Sk.', lastName: 'Shamim', age: 37},
]

const usersFullName = users.map(user => user.firstName + ' ' + user.lastName);

console.log(usersFullName);

// Output: ['Khan Rabiul', 'Anisul Islam', 'Shahidul Islam', 'Mr. Sabbir', 'Sk. Shamim']
Copy after login

উদাহরণ ৩ঃ

একটি array of object থেকে age এর সমষ্টি বের করতে হবে;

const users = [
    {firstName: 'Khan', lastName: 'Rabiul', age: 30},
    {firstName: 'Anisul', lastName: 'Islam', age: 20},
    {firstName: 'Shahidul', lastName: 'Islam', age: 25},
    {firstName: 'Mr.', lastName: 'Sabbir', age: 32},
    {firstName: 'Sk.', lastName: 'Shamim', age: 37},
]

const ageOver30 = users.filter(user => user.age > 30);
console.log(ageOver30);

//Output : {firstName: 'Mr.', lastName: 'Sabbir', age: 32},
//         {firstName: 'Sk.', lastName: 'Shamim', age: 37},

Copy after login

উদাহরণ ৫ঃ

একটি array of object থেকে যাদের age এর ক্রমানুসারে লিস্ট বের করতে হবে;

const users = [
    {firstName: 'Khan', lastName: 'Rabiul', age: 30},
    {firstName: 'Anisul', lastName: 'Islam', age: 20},
    {firstName: 'Shahidul', lastName: 'Islam', age: 25},
    {firstName: 'Mr.', lastName: 'Sabbir', age: 32},
    {firstName: 'Sk.', lastName: 'Shamim', age: 37},
]

const sortedByAge = users.sort((a, b) => a.age - b.age);
console.log(sortedByAge);

// Output:
//       {firstName: 'Anisul', lastName: 'Islam', age: 20} 
//       {firstName: 'Shahidul', lastName: 'Islam', age: 25}
//       {firstName: 'Khan', lastName: 'Rabiul', age: 30}
//       {firstName: 'Mr.', lastName: 'Sabbir', age: 32}
//       {firstName: 'Sk.', lastName: 'Shamim', age: 37}
Copy after login

উদাহরণ ৬ঃ উপরের উদাহরণ গুলো যদিও আমরা HoFs এর সাহায্যে সমাধান করেছি। এখানে একটি বিষয় লক্ষণীয় যে, প্রতি ক্ষেত্রে আমারা একই array of object input এ গ্রহণ করছি আর ভিন্ন operation চালাচ্ছি। যদি আমরা একটি function create করি, যেখানে একটি input এবং ভিন্ন operation এর জন্য ভিন্ন function callback এ ইনপুট নিতে পারবে। তা হলে function টি পুনঃ ব্যবহার যোগ্য ও আরো ডাইনামিক হবে।

const users = [
    {firstName: 'Khan', lastName: 'Rabiul', age: 30},
    {firstName: 'Anisul', lastName: 'Islam', age: 20},
    {firstName: 'Shahidul', lastName: 'Islam', age: 25},
    {firstName: 'Mr.', lastName: 'Sabbir', age: 32},
    {firstName: 'Sk.', lastName: 'Shamim', age: 37},
];

// আমাদের প্রয়োজনী ভিন্ন function সমূহঃ

// ০১, একটি array of object থেকে users full name লিস্ট তৈরী করতে হবে;
const getFullName = function(user) {
    return user.firstName + " " + user.lastName
}

// উদাহরণ ২, একটি array of object থেকে যাদের age ৩০ এর বেশি তাদের লিস্ট বের করতে হবে;
const getAgeOver30 = user => user.age < 30 ? user : null;

const calculate = function (users, callbackFunc) {
    let output = []; // Output store হবে 
    // যেহেতু input একটি array এবং এর প্রতিটি input এর উপর function কাজ করবে তাই  for loop 
    for(let i = 0; i <users.length; i++) {
        // output.push(callbackFunc(users[i]));

        // To handel null and undefined valu
        const result = callbackFunc(users[i]);
        if (result != null) {
            output.push(result);
        }
    }
    return output;
}

console.log(calculate(users, getAgeOver30));
// Output: 
//         {firstName: 'Anisul', lastName: 'Islam', age: 20}
//         {firstName: 'Shahidul', lastName: 'Islam', age: 25}
console.log(calculate(users, getFullName));

// Output: ['Khan Rabiul', 'Anisul Islam', 'Shahidul Islam', 'Mr. Sabbir', 'Sk. Shamim']
Copy after login
const numbers = [4,5,8,3,7,9,10,56];

const calculate = function(numbers, operation) {
    let output = [];
    for(let i = 0; i < numbers.length; i++) {
        if (output !== null) {
            output.push(operation(numbers[i]));
        }
    }
    return output;
}

// Double 
const double = function (number) {
    return number * 2;
}
// Triple 
const triple = function (number) {
    return number * 3;
}
// power 
const power4 = function (number) {
    return Math.pow(number,4);
}



console.log(calculate(numbers, double));
// Output: [8, 10, 16, 6, 14, 18, 20, 112]
console.log(calculate(numbers, triple));
// Output: [12, 15, 24, 9, 21, 27, 30, 168]
console.log(calculate(numbers, power4));
// Output: [256, 625, 4096, 81, 2401, 6561, 10000, 9834496]
Copy after login

অর্থাৎ function return পেলে বা arguments থেকে এক বা একাধিক function গ্রহণ করলে function টি, Higher Order function।


?‍? Recursion Function

যখন কোন সমস্যা সমাধানের জন্য একি কাজ বার বার করতে হয়, তখন তাকে Recursive Function বলে।

প্রত্যাশিত ফলাফল পাওয়ার জন্য কোন কাজ বার বার করা(function call করা)-কে recursion function বলে। **
উদাহরণ: ফ্যাক্টোরিয়াল ফাংশন

function factorial (num) {
    // base case

    if(num === 0) {
        return 1;
    }
    return num * factorial(num -1);
}

console.log(factorial(5));
// Output: 120
Copy after login

All About JavaScript Function

All About JavaScript Function

?‍? Recursion কীভাবে কাজ করেঃ

  1. Function Declaration
  2. Base Case
  3. Recursive Call command

? Function Declaration:

সাধারণ function যেভাবে declare করা হয়, এটাও ঠিক তেমন।

    function recursionFunction () {

    }
Copy after login

Base Case:

Base Case ই *recursion function* এর মূল ভিত্তি।

Base case ছাড়া *recursion function* একটি অসীম লুপে পরিণত হবে এবং প্রোগ্রাম ক্র্যাশ করবে।

*Recursion* ফাংশনে "base case" হলো এমন একটি শর্ত যা self-calling বন্ধ করার জন্য ব্যবহৃত হয়। এই শর্তটি পূরণ হলে ফাংশনটি আর নিজেকে কল করে না এবং একটি নির্দিষ্ট মান রিটার্ন করে।

`*Base case*` মূলত একটি স্টপিং পয়েন্ট, যা রিকারসনকে অসীম লুপে পরিণত হওয়া থেকে রক্ষা করে।

উপরের উদাহ্রন্টিতে *base case* হিসেবে ব্যবহৃত হয়েছে। এখানে যখন num = 0; হবে *return* value হবে 1 এবং *function* টি বন্ধ হবে। **

  if(num === 0) {
        return 1;
    }
Copy after login

? The Recursion Call command:

এই অংশটি মূলত একটি funciton বার বার *call* করার জন্য দায়ী। আবার অংশ থেকেই কাঙ্ক্ষিত ফলাফল নির্ধারিত হয়। উদাহরণ এরঃ

*return num * factorial(num -1);*

উদাহরণ ২ঃ একটি function তৈরী কর, যেটি প্রাপ্ত সংখ্যাকে বিপরীতক্রমে আউটপুট প্রদান করবে;

    // function declaration
    function decendingOrder (num) {
        let decndingNumbers = [];
        // base case
        if(num <= 0) {
            return;
        }
        console.log(num);

        decendingOrder(num - 1);
    }

   console.log( decendingOrder(5))
   // Output: 5 4 3 2 1
Copy after login

উদাহরণ ৩ঃ একটি function তৈরী কর, যেটি প্রাপ্ত stirng বিপরীতক্রমে আউটপুট প্রদান করবে;

   function reverseString (string) {
    if (string.length == 1) {
        return string;
    } else {
        return string.slice(-1) + reverseString(string.slice(0, -1));
    }
   }

   console.log(reverseString("string"));
   //Output: "gnirts"


Copy after login
// 1. slice মেথডটি স্ট্রিং থেকে একটি নির্দিষ্ট অংশ কাটে এবং নতুন একটি স্ট্রিং রিটার্ন করে।

// 2. এখানে slice(-1) ব্যবহার করা হয়েছে, যার মানে হলো স্ট্রিং এর শেষ অক্ষরটি কেটে নেওয়া।
// উদাহরণ: "string".slice(-1) এর আউটপুট হবে "g"।
// string.slice(0, -1):

// slice(0, -1) ব্যবহার করে স্ট্রিং এর প্রথম থেকে (ইন্ডেক্স 0 থেকে) শেষের ঠিক আগের অক্ষর পর্যন্ত সবকিছু কেটে নেওয়া হয়।
// উদাহরণ: "string".slice(0, -1) এর আউটপুট হবে "strin"।
// + অপারেটর:

// + অপারেটর এখানে স্ট্রিং কনক্যাটিনেশন (দুই বা ততোধিক স্ট্রিং একত্রিত করা) এর জন্য ব্যবহৃত হচ্ছে।
// উদাহরণ: "g" + "strin" এর আউটপুট হবে "gstrin"।


// reverseString("string") এর ধাপে ধাপে প্রসেসিং হবে:

// প্রথম কল: "g" + reverseString("strin")
// দ্বিতীয় কল: "n" + reverseString("stri")
// তৃতীয় কল: "i" + reverseString("str")
// চতুর্থ কল: "r" + reverseString("st")
// পঞ্চম কল: "t" + reverseString("s")
// ষষ্ঠ কল (Base case): "s"
//ফাইনালি, সব কনক্যাটিনেশন হয়ে উল্টো স্ট্রিং "gnirts" রিটার্ন হবে।
Copy after login

? Or, with loop

const str = "small";

function rev(str) {
    let revStr= "";
    for(let i = str.length -1; i>= 0; i--) {
        revStr += str[i];
    }
    return revStr;
}
console.log(rev(str));
// Output: llams
Copy after login

Recursion function কোড পড়া ও সহজে ভূল খুজে পেতে সাহায্য করে কিন্তু অসংখ্যবার function call করার কারণে performance খারাপ হতে পারে।


?‍? Currying

currying function এমন functional ধারণা যেখানে একাধিক arguments থাকলেও function টি এক সাথে একটির বেশি argument receive করে না। অর্থাৎ প্রতিটি argument এর জন্য একটি function declare ও return করে। তবে কোন function এর জন্য argument pass করলেও function টি সঠিকভাবে কাজ করতে পারে। এটি কোডের পুনঃব্যবহারযোগ্যতা বাড়ায় এবং কোডকে ছোট ও স্পষ্ট করে তোলে।

function add(a) {
    return function(b) {
        return function(c) {
            return a + b + c;
        }
    }
}

console.log(add(1)(2)(3)); // Output: 6
Copy after login

*একটি argument না দিয়েঃ *

function add(a) {
    return function(b) {
        return function(c) {
            return a + b ;
        }
    }
}

console.log(add(1)(2)()); // Output: 3

Copy after login

The above is the detailed content of All About JavaScript Function. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript in Action: Real-World Examples and Projects JavaScript in Action: Real-World Examples and Projects Apr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding the JavaScript Engine: Implementation Details Understanding the JavaScript Engine: Implementation Details Apr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Python vs. JavaScript: Development Environments and Tools Python vs. JavaScript: Development Environments and Tools Apr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

See all articles