|
4 | 4 | const a = 10; |
5 | 5 | const b = 20; |
6 | 6 | const sum = a + b; |
7 | | - console.log("Addition of two number", sum); |
| 7 | + console.log("Addition of two number:", sum); |
8 | 8 | // output: |
9 | 9 | // Addition of two number: 30 |
10 | 10 |
|
11 | | -// Using Function() |
12 | | -function sum(a, b){ |
13 | | - const c = a + b; |
14 | | -} |
15 | | -return c; |
16 | | -sum(4,5); |
| 11 | +// 2. Using Function() |
17 | 12 |
|
| 13 | + // Function to calculate the sum of two numbers using a temporary variable: |
| 14 | + function Sum(a, b){ |
| 15 | + const c = a + b; |
| 16 | + return c; |
| 17 | + } |
| 18 | + console.log("Sum:", Sum(4,5)); |
| 19 | + // Output: |
| 20 | + // Sum: 9 |
18 | 21 |
|
19 | | -// 2. One-Line Addition (Used for Console testing or demo purpose) |
20 | | - Console.log(10+5); |
| 22 | + // OR |
| 23 | + |
| 24 | + // Function to return the sum of two numbers directly |
| 25 | + function Sum(a, b) { |
| 26 | + return a + b; |
| 27 | + } |
| 28 | + console.log(Sum(3, 7)); |
21 | 29 | // Output: |
22 | | - // 15 |
| 30 | + // 10 |
| 31 | + |
| 32 | +// 3. Using Arrow Function |
| 33 | + // One-liner arrow function to add two numbers |
| 34 | + const add = (a, b) => a + b; |
| 35 | + console.log(add(10, 15)); |
| 36 | + // Output: |
| 37 | + // 25 |
| 38 | + |
| 39 | + // OR |
| 40 | + |
| 41 | + // Arrow function to add two numbers using a variable and return |
| 42 | + const Add = (a, b) => { |
| 43 | + const sum = a + b; |
| 44 | + return sum; |
| 45 | + } |
| 46 | + console.log("Sum of Two Number:", Add(3,2)); |
| 47 | + // Output: |
| 48 | + // 5 |
23 | 49 |
|
24 | | -// 3. Using "prompt()" It take Inputs from User, Convert to number and Perform Addition – Runs only in browser |
25 | | - let a = Number(prompt("Enter first number:")); |
26 | | - let b = Number(prompt("Enter second number:")); |
27 | | - console.log("Sum:", a + b); |
| 50 | +// 4. Using Rest Parameters ( Used For Multiple Inputs) |
| 51 | + function addAll(...nums) { |
| 52 | + let sum = 0; |
| 53 | + for (let n of nums) { |
| 54 | + sum += n; |
| 55 | + } |
| 56 | + return sum; |
| 57 | + } |
| 58 | + console.log(addAll(1, 2, 3, 4)); |
28 | 59 | // Output: |
29 | | - // Enter frist number: 2 |
30 | | - // Enter second number: 8 |
31 | | - // Sum: 10 |
| 60 | + // 10 |
32 | 61 |
|
33 | | -// OR |
| 62 | +//5. Using prompt() (User Input) – only browser |
| 63 | +let arr = [1, 2, 3, 4]; |
| 64 | +let Sum = arr.reduce((a, b) => a + b, 0); |
| 65 | +console.log("Sum:", sum); // Output: 10 |
0 commit comments