repl.it
@cmclau01/

factorial loop

JavaScript

create a function that accepts a number for an argument and returns its factorial.

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
/*

[Factorial] - Exercise Link

Create the function factorial(num) that returns the factorial of the parameter.

Not sure what the factorial is? Check this [link for a refresher!](http://www.rapidtables.com/math/algebra/Factorial.htm)

**Example:**

- INPUT: `factorial(4);`
- Return Value: `24`
// 4 * 3 * 2 * 1
*/
function factorial(num) {
  debugger;
  let factNum = 0;
  for (let i = (num - 1); i > 0; i--) {
//we need num to decrement and then be multiplied by the the new value.
    factNum = num *= i;
  }
  return factNum;
}
factorial(5);

/* Condensed solution:
function factorial(num){
	var total = 1;
	
	for(num; num >1; num--){
		total*= num;
	}

	return total;
}
  setting the total to 1 multiplies it by the base value of num, returning num and then decrementing each iteration thereafter. this condenses the code by eliminating the need for an additional variable to multiply num by. 
*/






















































































// TEST SPECS


// console.log(factorial(4));
// => logs 24 since (4*3*2*1) === 24

// console.log(factorial(5));
// => logs 120 since (5*4*3*2*1) === 120
Native Browser JavaScript
?