0% found this document useful (0 votes)
9 views24 pages

M1 FS Ia1

The document provides a comprehensive overview of JavaScript, highlighting its characteristics, differences from Java, and various programming concepts such as variable declarations (var, let, const), data types, loops, functions, and object creation. It explains the usage of arrays, string methods, and the distinctions between for and while loops, along with examples for better understanding. Additionally, it covers security, performance, and best practices in JavaScript programming.

Uploaded by

naiksharmu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views24 pages

M1 FS Ia1

The document provides a comprehensive overview of JavaScript, highlighting its characteristics, differences from Java, and various programming concepts such as variable declarations (var, let, const), data types, loops, functions, and object creation. It explains the usage of arrays, string methods, and the distinctions between for and while loops, along with examples for better understanding. Additionally, it covers security, performance, and best practices in JavaScript programming.

Uploaded by

naiksharmu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

1. Define JavaScript. How is it different from Java?

Ans:

JavaScript

• Interpreted Language (Runs directly in the browser without compilation).

• Used for web development (frontend: DOM manipulation, backend: Node.js).

• Dynamically Typed (Variable types are assigned at runtime).

let data = 10; // Number

data = "Hello"; // No error (Type changed)

console.log(data);

• Single-threaded (Uses an event-driven, non-blocking model).

• Lightweight and mainly used for client-side scripting.

Example (JavaScript - Dynamic Content Update)

document.getElementById("demo").innerHTML = "Hello, JavaScript!";

This changes the content of an HTML element dynamically.

Java

• Compiled Language (Requires compilation into bytecode for JVM).

• Used for enterprise applications, mobile (Android), and backend development.

• Statically Typed (Variable types must be declared explicitly).

int data = 10;

data = "Hello"; // ERROR: Type mismatch

• Supports Multithreading (Can run multiple tasks concurrently).

• Requires JVM to run (Platform-independent via JVM).

Example (Java - Simple Program)

public class HelloWorld {

public static void main(String[] args) {

System.out.println("Hello, Java!");

}
}

This prints "Hello, Java!" to the console.

Security

• JavaScript: Less secure, vulnerable to XSS and injection attacks as it runs in browsers.

• Java: More secure, runs in JVM with built-in security features like bytecode
verification.

Performance

• JavaScript: Slower, interpreted in browsers but optimized with JIT compilation.

• Java: Faster, compiled into bytecode and supports multithreading for better
performance.

Key Differences in One Line

JavaScript is mainly used for web interactivity, while Java is used for general-purpose
programming, including mobile and backend applications.

2. Explain the difference between var, let, and const in JavaScript with examples.

Ans:

1. var (Function-scoped, Re-declarable)

• Scoped to the function it is declared in (not block-scoped).


• Can be re-declared and reassigned.
• Hoisted with an initial value of undefined.
• Attached to the window object in the browser.

Example:

var x = 10;
if (true) {
var x = 20; // Re-declaration allowed
console.log(x); // Output: 20
}
console.log(x); // Output: 20 (Var is not block-scoped)
Hoisting Example:
console.log(x); // Output: undefined
var x = 5;

2. let (Block-scoped, No Re-declaration)

• Scoped to the block {} it is declared in.


• Cannot be re-declared but can be reassigned.
• Hoisted but not initialized (Accessing before declaration causes an error).
• Not attached to the window object.

Example:

let y = 10;
if (true) {
let y = 20; // Creates a new variable inside this block
console.log(y); // Output: 20
}
console.log(y); // Output: 10 (Different from `var`)

Re-declaration Error

let a = 5;
let a = 10; // Error: 'a' has already been declared

Hoisting Example (Throws Error):


console.log(y); // Reference Error: Cannot access 'y' before
initialization
let y = 10;

3. const (Block-scoped, Immutable)

• Scoped to the block {}.


• Cannot be re-declared or reassigned.
• Hoisted but not initialized (must be assigned a value at declaration).
• Used for constants, arrays, and objects (but object properties can be modified).

Example:

const z = 30;
console.log(z); // Output: 30

Reassignment Error

const z = 30;
z = 40; // Error: Assignment to constant variable
Must be initialized

const w; // Error: Missing initializer in const declaration

Modifying Object Properties (Allowed)


const person = { name: "Alice", age: 25 };
person.age = 26; // Allowed
console.log(person.age); // Output: 26

Reassigning Object (Not Allowed)


const person = { name: "Alice" };
person = { name: "Bob" }; // TypeError: Assignment to constant variable

Summary (When to Use What?)

• Use var → Avoid using it due to function scope issues.


• Use let → When the value needs to change.
• Use const → When the value should not change (best for constants & objects).

3. Discuss different data types in JavaScript? List and explain any four.

Data Types in JavaScript

JavaScript has two main categories of data types:

1. Primitive Data Types (immutable, stored by value)


2. Non-Primitive (Reference) Data Types (mutable, stored by reference)

Primitive Data Types

1. Number – Represents numeric values (integers and floating-point numbers).


2. String – Represents textual data enclosed in quotes ("", '', or ````).
3. Boolean – Represents true or false values.
4. Undefined – A variable that has been declared but not assigned a value.
5. Null – Represents an intentional absence of value.
6. BigInt – Used for very large numbers beyond Number limits.
7. Symbol – A unique identifier used in objects.

Non-Primitive (Reference) Data Types

1. Object – Collection of key-value pairs.


2. Array – A special type of object that stores ordered lists.
3. Function – A block of reusable code.
Explanation of Four Data Types

1. Number

• Used to store integers and floating-point values.


• Example:

let age = 25; // Integer

let price = 99.99; // Floating-point number

2. String

• Used to store text, enclosed in "", '', or ````.


• Example:

let name = "John";

let message = 'Hello, World!';

let greeting = `Welcome, ${name}!`; // Template literals

3. Boolean

• Represents true or false values.


• Example:

let isLoggedIn = true;

let hasPermission = false;

4. Object

• A collection of key-value pairs, used to store complex data.


• Example:

let person = {

name: "Alice",

age: 30,
isStudent: false

};

console.log(person.name); // Output: Alice

4. How do you create an array in JavaScript? Demonstrate with an example.


Ans:

Creating an Array in JavaScript

An array in JavaScript is a data structure used to store multiple values in a single variable.
Arrays can hold different data types, such as numbers, strings, objects, and even other arrays.

Ways to Create an Array

1. Using Square Brackets [] (Recommended)

This is the most common and preferred way to create an array in JavaScript.

let fruits = ["Apple", "Banana", "Cherry"];

console.log(fruits); // Output: ["Apple", "Banana", "Cherry"]

• The elements are enclosed within square brackets [] and separated by commas.
• JavaScript arrays are zero-indexed, meaning the first element is at index 0, the
second at 1, and so on.

Example of accessing elements:

console.log(fruits[0]); // Output: "Apple"

console.log(fruits[1]); // Output: "Banana"

console.log(fruits[2]); // Output: "Cherry"

2. Using the Array Constructor

Another way to create an array is by using the Array constructor.

let numbers = new Array(10, 20, 30);


console.log(numbers); // Output: [10, 20, 30]

• This method is less common because it can be confusing.


• If a single number is passed, it creates an empty array of that length instead of an
array containing that number.

Example:

let arr = new Array(5);

console.log(arr); // Output: [empty × 5] (Creates an empty array with 5 slots)

Best Practice: It is recommended to use square brackets [] instead of the Array


constructor to avoid unexpected behavior.

3. Creating an Empty Array

If you want to create an empty array and add elements later:

let emptyArray = [];

console.log(emptyArray); // Output: []

4. Mixed Data Type Arrays

JavaScript allows arrays to contain elements of different data types.

let mixedArray = ["Hello", 42, true, { name: "Alice" }];

console.log(mixedArray);

// Output: ["Hello", 42, true, { name: "Alice" }]

Conclusion

JavaScript arrays are flexible and easy to use. They can be created using square brackets []
(preferred) or the Array constructor. Arrays can hold different data types and support
various operations to manipulate data efficiently.

5. Differentiate between for loop and while loop in JavaScript.

Ans:
Difference Between for Loop and while Loop in JavaScript

Both for and while loops are used to execute a block of code repeatedly, but they differ in
syntax and usage.

1️⃣ for Loop

• Used when the number of iterations is known beforehand.


• Consists of three parts: initialization, condition, and increment/decrement in a
single line.
• Best suited for iterating over arrays or counting loops.

Example:

for (let i = 1; i <= 5; i++) {

console.log(i); // Output: 1, 2, 3, 4, 5

2️⃣ while Loop

• Used when the number of iterations is not known in advance.


• Executes the block as long as the condition is true.
• Best suited for waiting for a specific condition to become false.

Example:

let i = 1;

while (i <= 5) {

console.log(i); // Output: 1, 2, 3, 4, 5

i++;

Key Differences

• Use for loop when the iteration count is fixed or predefined.


• Use while loop when the iteration count depends on a condition that may change
dynamically.
• for loop is generally used for structured looping, while while loop is used when
looping depends on runtime conditions.

6. Write a JavaScript function to find the factorial of a given number.

Ans:

Using Iteration (for loop)

function factorial(n) {

let result = 1;

for (let i = 1; i <= n; i++) {

result *= i;

return result;

console.log(factorial(5)); // Output: 120

Using Recursion

function factorialRecursive(n) {

if (n === 0 || n === 1) return 1;

return n * factorialRecursive(n - 1);

console.log(factorialRecursive(5)); // Output: 120

7.Explain how JavaScript objects are created. Illustrate with an example using object
properties and methods.

How JavaScript Objects Are Created


In JavaScript, objects are used to store multiple properties and methods in a single entity.
Objects hold key-value pairs, where keys are property names, and values can be data or
functions.

Ways to Create Objects in JavaScript


1. Using Object Literals (Recommended)

The most common and simplest way to create an object is by using curly braces {}.

let person = {
name: "John",
age: 25,
city: "New York",
greet: function() {
return "Hello, my name is " + this.name + ".";
}
};

console.log(person.name); // Output: John


console.log(person.greet()); // Output: Hello, my name is John.

• The name, age, and city are properties of the object.


• The greet function is a method (a function inside an object).
• The this keyword refers to the current object (person in this case).

2. Using the new Object() Constructor

Another way to create an object is by using the Object constructor.

let car = new Object();


car.brand = "Tesla";
car.model = "Model S";
car.start = function() {
return this.brand + " " + this.model + " is starting...";
};

console.log(car.brand); // Output: Tesla


console.log(car.start()); // Output: Tesla Model S is starting...

• This method is less common and not preferred over object literals.

3. Using Constructor Functions

A constructor function allows you to create multiple objects with similar properties.

function Person(name, age) {


this.name = name;
this.age = age;
this.greet = function() {
return "Hello, my name is " + this.name + ".";
};
}

let person1 = new Person("Alice", 30);


let person2 = new Person("Bob", 28);

console.log(person1.greet()); // Output: Hello, my name is Alice.


console.log(person2.greet()); // Output: Hello, my name is Bob.

• The new keyword creates a new object based on the Person constructor.

4. Using Object.create()

This method creates an object with a specified prototype.

let prototypePerson = {
greet: function() {
return "Hello, my name is " + this.name + ".";
}
};

let person3 = Object.create(prototypePerson);


person3.name = "Charlie";

console.log(person3.greet()); // Output: Hello, my name is Charlie.

• This method is useful when you want to inherit properties from another object.

Conclusion

JavaScript objects can be created in multiple ways, but the object literal method ({}) is the
most commonly used due to its simplicity and readability. Objects help in structuring data
efficiently using properties (variables) and methods (functions).

8. Describe the different types of string methods available in JavaScript with examples.

Ans:

Different Types of String Methods in JavaScript

JavaScript provides various built-in string methods to manipulate and process text. These
methods allow performing operations like searching, modifying, splitting, and formatting
strings.
1. Finding the Length of a String

The length property returns the number of characters in a string.

let str = "Hello, World!";

console.log(str.length); // Output: 13

2. Changing Case

• toUpperCase(): Converts all characters to uppercase.


• toLowerCase(): Converts all characters to lowercase.

let text = "JavaScript";

console.log(text.toUpperCase()); // Output: JAVASCRIPT

console.log(text.toLowerCase()); // Output: javascript

3. Extracting Parts of a String

• slice(start, end): Extracts part of a string from start index to end index (excluding
end).
• substring(start, end): Similar to slice(), but does not accept negative values.
• substr(start, length): Extracts a substring starting from start and takes length
characters.

let sentence = "Programming is fun!";

console.log(sentence.slice(0, 11)); // Output: Programming

console.log(sentence.substring(5, 11)); // Output: amming

console.log(sentence.substr(5, 6)); // Output: amming

4. Replacing Text in a String

• replace(searchValue, newValue): Replaces the first occurrence of searchValue with


newValue.
• replaceAll(searchValue, newValue): Replaces all occurrences.

let message = "Hello, JavaScript!";


console.log(message.replace("JavaScript", "World")); // Output: Hello, World!

console.log("apple apple".replaceAll("apple", "banana")); // Output: banana banana

5. Searching in a String

• indexOf(substring): Returns the first index of substring, or -1 if not found.


• lastIndexOf(substring): Returns the last index of substring.
• includes(substring): Returns true if substring is found, otherwise false.
• startsWith(substring): Checks if the string starts with substring.
• endsWith(substring): Checks if the string ends with substring.

let phrase = "Learning JavaScript is fun!";

console.log(phrase.indexOf("JavaScript")); // Output: 9

console.log(phrase.lastIndexOf("is")); // Output: 18

console.log(phrase.includes("fun")); // Output: true

console.log(phrase.startsWith("Learning")); // Output: true

console.log(phrase.endsWith("fun!")); // Output: true

6. Removing Whitespaces

• trim(): Removes whitespace from both ends of a string.


• trimStart(): Removes whitespace from the start.
• trimEnd(): Removes whitespace from the end.

let input = " Hello World! ";

console.log(input.trim()); // Output: "Hello World!"

console.log(input.trimStart()); // Output: "Hello World! "

console.log(input.trimEnd()); // Output: " Hello World!"

7. Splitting a String

The split(separator) method splits a string into an array based on a separator.

let names = "Alice,Bob,Charlie";


console.log(names.split(",")); // Output: ["Alice", "Bob", "Charlie"]

8. Concatenating Strings

• concat(str1, str2, ...): Joins multiple strings together.


• The + operator also concatenates strings.

let firstName = "John";

let lastName = "Doe";

console.log(firstName.concat(" ", lastName)); // Output: John Doe

console.log(firstName + " " + lastName); // Output: John Doe

Conclusion

JavaScript provides various string methods to manipulate and process text efficiently.
These methods help with searching, modifying, extracting, formatting, and splitting
strings based on different needs.

9. Explain if-else and switch-case statements in JavaScript with examples.

Ans:

If-Else and Switch-Case Statements in JavaScript

Control flow statements like if-else and switch-case allow JavaScript to execute different
blocks of code based on conditions.

1. If-Else Statement
The if-else statement executes a block of code if a condition is true and another block if the
condition is false.

Syntax
if (condition) {
// Code executes if condition is true
} else {
// Code executes if condition is false
}
Example
let age = 18;

if (age >= 18) {


console.log("You are eligible to vote.");
} else {
console.log("You are not eligible to vote.");
}

Output:
You are eligible to vote.

Else-If Ladder

Used when multiple conditions need to be checked.

let marks = 85;

if (marks >= 90) {


console.log("Grade: A");
} else if (marks >= 75) {
console.log("Grade: B");
} else if (marks >= 50) {
console.log("Grade: C");
} else {
console.log("Grade: F");
}

Output:
Grade: B

2. Switch-Case Statement
The switch statement is used when there are multiple possible values for a variable, and
different actions need to be taken based on those values.

Syntax
switch (expression) {
case value1:
// Code to execute if expression matches value1
break;
case value2:
// Code to execute if expression matches value2
break;
default:
// Code to execute if none of the cases match
}

Example
let day = "Monday";

switch (day) {
case "Monday":
console.log("Start of the workweek.");
break;
case "Friday":
console.log("Weekend is near!");
break;
case "Sunday":
console.log("It's a holiday.");
break;
default:
console.log("It's a regular day.");
}

Output:
Start of the workweek.

Break and Default in Switch-Case

The break statement stops further execution once a case is matched. The default case runs
if none of the cases match the given value.

Differences Between If-Else and Switch-Case


The if-else statement is used for complex conditions where logical operators like && or ||
may be needed. It executes each condition sequentially.

The switch-case statement is best when checking a single variable against multiple fixed
values. It directly jumps to the matched case, making it more efficient for such scenarios.

Use if-else when checking conditions with relational or logical operators. Use switch-
case when checking a variable against multiple fixed values.

10. Write a JavaScript program to find the largest number in an array using a loop.

Ans:

Program
function findLargestNumber(arr) {
if (arr.length === 0) {
return "Array is empty";
}

let largest = arr[0];

for (let i = 1; i < arr.length; i++) {


if (arr[i] > largest) {
largest = arr[i];
}
}

return largest;
}

let numbers = [12, 45, 78, 23, 89, 34];


console.log("Largest number:", findLargestNumber(numbers));

11. Write a script that Logs "Hello, World!" to the console. Create a script that calculates
the sum of two numbers and displays the result in an alert box.

Ans:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LAB 1</title>
<link rel="icon" href="data:,">

</head>
<body>
<h1>WELCOME TO SEE HELLO WORLD IN CONSOLE</h1>
<div id="result"></div>

<script>
console.log("HELLO WORLD");

let num1 = parseFloat(prompt("Enter first number:"));


let num2 = parseFloat(prompt("Enter second number:"));

let sum = num1 + num2;

console.log("The sum is:", sum);

document.getElementById("result").innerHTML = `<h1>The sum is:


${sum}</h1>`;

</script>
</body>
</html>
12. Create an array of 5 cities and perform the following operations: Log the total number
of cities. Add a new city at the end. Remove the first city. Find and log the index of a
specific city.

Ans:

/*const readline = require("readline-sync");

let cities = [];


let cityCount = parseInt(readline.question("How many cities do you want to
enter? "), 10);

for (let i = 0; i < cityCount; i++) {


cities.push(readline.question(`Enter city ${i + 1}: `));
}

console.log("Total number of cities:", cities.length);

let newCity = readline.question("Enter a new city to add: ");


cities.push(newCity);
console.log("Cities:", cities);

let removeCity = readline.question("Enter a city to remove: ");


let removeIndex = cities.indexOf(removeCity);
cities.shift();
console.log("Cities:", cities);

let searchCity = readline.question("Enter a city to find its index: ");


let cityIndex = cities.indexOf(searchCity);
console.log(`Index of ${searchCity}:`, cityIndex);
*/

const prompt = require("prompt-sync");

let cities = [];


let cityCount = parseInt(prompt("Enter number of cities you want to enter "),
10);

for (let i = 0; i < cityCount; i++) {


cities.push(prompt(`Enter city ${i + 1}: `));
}

console.log("Total number of cities:", cities.length);

let newCity = prompt("Enter a new city to add: ");


cities.push(newCity);
console.log("Cities:", cities);
let removeCity = prompt("Enter a city to remove: ");
let removeIndex = cities.indexOf(removeCity);
cities.shift();
console.log("Cities:", cities);

let searchCity = prompt("Enter a city to find its index: ");


let cityIndex = cities.indexOf(searchCity);
console.log(`Index of ${searchCity}:`, cityIndex)

13. Read a string from the user, Find its length. Extract the word "JavaScript" using
substring() or slice(). Replace one word with another word and log the new string.

Ans:

const prompt = require("prompt-sync")();


let string= prompt("Enter a string: ");
console.log("Length of the string:", string.length);

let startInd = string.indexOf("JavaScript");

if(startInd!= -1){
let extractedWord=string.slice(startInd, startInd+10);
console.log("Extracted word:", extractedWord);
}
else{
console.log("The word 'JavaScript' was not found in the string.");
}

let wordtobeReplaced = prompt("Enter the word to replace: ");


let newWord = prompt("Enter new word to be replaced: ");
let newstring = string.replace(wordtobeReplaced, newWord);
console.log("Modified string:", newstring);

14. Write a function isPalindrome(str) that checks if a given string is a palindrome (reads
the same backward).

Ans:

const prompt = require("prompt-sync")();

function isPalindrome(word) {
let reversed = word.split("").reverse().join("");
console.log("Reversed String:", reversed);

return word === reversed;


}

let userInput = prompt("Enter a word: ");


console.log("Is palindrome:", isPalindrome(userInput));

15. Write a JavaScript program to declare variables of different data types (string,
number, boolean, array, and object) and display their values using console.log()

Ans:

JavaScript Program to Declare Variables of Different Data Types and Display


Their Values

JavaScript supports various data types, including string, number, boolean, array, and object.
The following program demonstrates how to declare these data types and print their values
using console.log().

Program
// String
let name = "John Doe";
console.log("String:", name);

// Number
let age = 25;
console.log("Number:", age);

// Boolean
let isStudent = true;
console.log("Boolean:", isStudent);

// Array
let colors = ["Red", "Blue", "Green"];
console.log("Array:", colors);

// Object
let person = {
firstName: "John",
lastName: "Doe",
age: 25,
isStudent: true
};
console.log("Object:", person);

Explanation
• A string variable is declared and assigned a name.
• A number variable is assigned an integer value.
• A boolean variable stores a true/false value.
• An array is declared to hold multiple values.
• An object is created to store multiple properties of a person.
• The console.log() function is used to display each variable's value.

Output
String: John Doe
Number: 25
Boolean: true
Array: [ 'Red', 'Blue', 'Green' ]
Object: { firstName: 'John', lastName: 'Doe', age: 25, isStudent: true }

16. Write a JavaScript program to create an array of five numbers. Find and print the
largest and smallest numbers from the array.

Ans:

function findLargestAndSmallest(arr) {
if (arr.length === 0) {
return "Array is empty";
}

let largest = arr[0];


let smallest = arr[0];

for (let i = 1; i < arr.length; i++) {


if (arr[i] > largest) {
largest = arr[i];
}
if (arr[i] < smallest) {
smallest = arr[i];
}
}

console.log("Largest number:", largest);


console.log("Smallest number:", smallest);
}

let numbers = [10, 25, 8, 42, 17];


findLargestAndSmallest(numbers);

17. Write a JavaScript function that takes a string as input and: • Converts it to uppercase
• Reverses the string • Counts the number of vowels in the string

Ans:
function processString(input) {
if (typeof input !== "string" || input.length === 0) {
return "Invalid input";
}

// Convert to uppercase
let upperCaseStr = input.toUpperCase();

// Reverse the string


let reversedStr = input.split("").reverse().join("");

// Count vowels
let vowelCount = 0;
let vowels = "aeiouAEIOU";

for (let char of input) {


if (vowels.includes(char)) {
vowelCount++;
}
}

console.log("Uppercase:", upperCaseStr);
console.log("Reversed:", reversedStr);
console.log("Number of vowels:", vowelCount);
}

// Example usage
processString("hello world");

18. Write a JavaScript function to generate and print the first n Fibonacci numbers using a
loop. The function should take n as input.

Ans:

JavaScript Function to Generate Fibonacci Series

This function takes n as input and generates the first n Fibonacci numbers using a loop.

Program
function generateFibonacci(n) {
if (n <= 0) {
console.log("Please enter a positive integer");
return;
}

let fibonacciSeries = [];


// First two Fibonacci numbers
let a = 0, b = 1;

for (let i = 0; i < n; i++) {


fibonacciSeries.push(a);
let next = a + b;
a = b;
b = next;
}

console.log("Fibonacci Series:", fibonacciSeries.join(", "));


}

// Example usage
generateFibonacci(10);

Explanation

• The function checks if n is a valid positive number.


• It initializes a and b as the first two Fibonacci numbers (0 and 1).
• A loop runs n times, adding each Fibonacci number to the array.
• The next number is computed as the sum of the previous two numbers.
• The final series is printed in a comma-separated format.

Output
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34

19. Write a JavaScript function that takes an array of numbers as input and returns the
sum of all elements.

Ans:

JavaScript Function to Calculate the Sum of an Array

This function takes an array of numbers as input and returns the sum of all elements.

Program
function sumArray(arr) {
if (!Array.isArray(arr) || arr.length === 0) {
return "Invalid input";
}

let sum = 0;

for (let num of arr) {


sum += num;
}

return sum;
}
// Example usage
let numbers = [10, 20, 30, 40, 50];
console.log("Sum of array elements:", sumArray(numbers));

Explanation

• The function checks if the input is a valid non-empty array.


• It initializes sum to 0 and iterates through the array, adding each number to sum.
• The final sum is returned.

Output
Sum of array elements: 150

You might also like