JavaScript "new Function" Syntax : JS "new Function" Syntax

Hello ! friends , आपने अभी तक JavaScript में normally functions को callback , arrow function और या तो anonymous function के रूप में ही use किया होगा। लेकिन JavaScript में एक और तरीका है जिससे हम function को define कर सकते हैं।

Yes ! new Function() syntax का use करके भी आप JavaScript में functions define कर सकते हैं , और need के according उसमे arguments भी pass कर सकते हैं।

इस article में हम new Function() को अच्छे से easy examples के साथ समझेंगे।

JS "new Function" syntax

इस type के functions को define करने का syntax कुछ इस तरह से है -

let func = new Function ([arg1, arg2, ...argN], functionBody);

arguments आप चाहे कितने ही pass करें , function body last में होना mandatory है। इस type के functions में function body / definition को single या double inverted comma के अंदर लिखा जाता है।

JS "new Function" Example

, चलिए अब कुछ easy examples देख लेते हैं।

JS "new Function" Example

let sayHello = new Function('console.log("Hello !")'); sayHello(); //function call.

Output :

Hello !

JS function with arguments

function में arguments handle करने के लिए आप Function() के अंदर comma separated define का रसकते हैं।

let x = new Function('a', 'b' , 'console.log(a+b)'); x(10, 20); x(45, 56); // or. let y = new Function('a', 'b', 'c' , 'console.log(a+b+c)'); y(12,23,45);

Output :

30
101
80

Other ways to define parameters

हालाँकि आप चाहे तो parameters को अलग अलग comma से define न करके एक साथ string में comma separated भी define कर सकते हैं। जैसे ऊपर दिए गए example को कुछ इस तरह से भी कर सकते हैं।

let x = new Function('a,b' , 'console.log(a+b)'); x(10, 20); x(45, 56); // or. let y = new Function('a,b,c' , 'console.log(a+b+c)'); y(12,23,45);

Output :

30
101
80

use backticks for multiline statements

multi line statements लिखने के लिए आप backticks (` `) का use कर सकते हैं।

let x = new Function(` console.log("Hi"); console.log("Hello"); console.log("Welcome"); `); x();

Output :

Hi
Hello
Welcome

I Hope, अब आपको JavaScript में new Function syntax समझ आ गया होगा।

Recent Blogs

Loading ...

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook