How to use the eval() function In Javascript
In this method we will use the eval() function. This method is used to evaluate the string. In this method we take take the string argument and then executes the given operation.
Example: To demonstrate utilizing the `join` method and `eval` function to dynamically calculate the sum of elements in a given array.
Javascript
function sumArray(arr) { let expression = arr.join( '+' ); return eval(expression); } const arr = [2.3, 4.7, 4, 3]; console.log( "Input:" , arr); console.log( "Output:" , sumArray(arr)); |
Output
Input: [ 2.3, 4.7, 4, 3 ] Output: 14
Time complexity: O(N)
Space complexity: O(N)
How to find the Sum of an Array of Numbers in JavaScript ?
Array in JavaScript is a data structure that is used to store a list of data. It is a contiguous block of memory which is used to store the data. As it is contiguous in memory we can access its elements in constant time.
There are several different methods for finding the sum of an array of numbers using JavaScript which are as follows:
Table of Content
- Using for Loop
- Using reduce () Method
- Using the eval() function
Contact Us