Share your knowledge with other learners . . . Login Register

Blogs ❯❯ JavaScript

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

Top Blogs

Loading ...



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 समझ आ गया होगा।

Give Feedback

like-image 3.

Recent Blogs

Loading ...

Rahul Kumar

Rahul Kumar

Hi ! My name is Rahul Kumar Rajput. I'm a back end web developer and founder of learnhindituts.com. I live in Uttar Pradesh (UP), India and I love to talk about programming as well as writing technical tutorials and tips that can help to others.

Get connected with me. :) LinkedIn Twitter Instagram Facebook