C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
JavaScript FunctionsJavaScript functions are used to perform operations. We can call JavaScript function many times to reuse the code. Advantage of JavaScript functionThere are mainly two advantages of JavaScript functions.
JavaScript Function SyntaxThe syntax of declaring function is given below. function functionName([arg1, arg2, ...argN]){ //code to be executed } JavaScript Functions can have 0 or more arguments. JavaScript Function ExampleLet’s see the simple example of function in JavaScript that does not has arguments. <script> function msg(){ alert("hello! this is message"); } </script> Output of the above exampleJavaScript Function ArgumentsWe can call function by passing arguments. Let’s see the example of function that has one argument. <script> function getcube(number){ alert(number*number*number); } </script> Output of the above exampleFunction with Return ValueWe can call function that returns a value and use it in our program. Let’s see the example of function that returns value. <script> function getInfo(){ return "hello TheDeveloperBlog! How r u?"; } </script> <script> document.write(getInfo()); </script> Output of the above exampleJavaScript Function ObjectIn JavaScript, the purpose of Function constructor is to create a new Function object. It executes the code globally. However, if we call the constructor directly, a function is created dynamically but in an unsecured way. Syntaxnew Function ([arg1[, arg2[, ....argn]],] functionBody) Parameterarg1, arg2, .... , argn - It represents the argument used by function. functionBody - It represents the function definition. JavaScript Function MethodsLet's see function methods with description.
JavaScript Function Object ExamplesExample 1Let's see an example to display the sum of given numbers. <script> var add=new Function("num1","num2","return num1+num2"); document.writeln(add(2,5)); </script> Output: 7 Example 2Let's see an example to display the power of provided value. <script> var pow=new Function("num1","num2","return Math.pow(num1,num2)"); document.writeln(pow(2,3)); </script> Output: 8
Next TopicJavascript Objects
|