Blogs ❯❯ JavaScript
Loading ...
If tutorials available on this website are helpful for you, please whitelist this website in your ad blocker😭 or Donate to help us ❤️ pay for the web hosting to keep the website running.
Image by Ferenc Almasi on Unsplash
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 के साथ समझेंगे।
इस 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 के अंदर लिखा जाता है।
, चलिए अब कुछ easy examples देख लेते हैं।
let sayHello = new Function('console.log("Hello !")');
sayHello(); //function call.
Output :
Hello !
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
हालाँकि आप चाहे तो 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
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 समझ आ गया होगा।
3.
Loading ...
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