Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path040-fn-expression.js
More file actions
Latest commit
105 lines (80 loc) · 2.2 KB
/
Copy path040-fn-expression.js
File metadata and controls
105 lines (80 loc) · 2.2 KB
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
// 1: RETURN VALUES
// function add(a, b) {
// return a + b;
// }
// const result = add(5, 3);
// console.log(result); // 8
// 2: FUNCTIONS WITHOUT RETURN
// function greet(name) {
// console.log("Hello, " + name);
// }
// const greeting = greet("Sarah");
// console.log(greeting); // undefined
// 3: RETURN STOPS EXECUTION
functioncheckAge(age){
if(age<18){
return"Too young";
}
return"Welcome!";
console.log("This will never run");// Unreachable code
}
constmessage=checkAge(15);
console.log(message);// "Too young"
// 4: RETURNING DIFFERENT DATA TYPES
// Returning a boolean
// function isEven(number) {
// return number % 2 === 0;
// }
// console.log(isEven(4)); // true
// Returning an array
// function getColors() {
// return ["red", "green", "blue"];
// }
// const colors = getColors();
// console.log(colors[0]); // "red"
// // Returning an object
// function createUser(name, age) {
// return {
// name: name,
// age: age,
// active: true
// };
// }
// const user = createUser("John", 25);
// console.log(user.name); // "John"
// 5: FUNCTION EXPRESSIONS
// const sayHello = function() {
// console.log("Hello!");
// };
// sayHello(); // "Hello!"
// 6: DECLARATION VS EXPRESSION
// This works - function declaration
greet();
functiongreet(){
console.log("Hello from declaration!");
}
// This causes an error - function expression
sayGoodbye();// Error: Cannot access 'sayGoodbye' before initialization
constsayGoodbye=function(){
console.log("Goodbye from expression!");
};
// 7: NAMED FUNCTION EXPRESSIONS
constfactorial=functioncalculateFactorial(n){
if(n<=1)return1;
returnn*calculateFactorial(n-1);
};
console.log(factorial(5));// 120
// 8: PRACTICAL EXAMPLE
constcalculateDiscount=function(price,discountPercent){
if(price<=0){
return0;
}
constdiscount=price*(discountPercent/100);
constfinalPrice=price-discount;
returnfinalPrice;
};
constoriginalPrice=100;
constdiscountedPrice=calculateDiscount(originalPrice,20);
console.log("Original: $"+originalPrice);// "Original: $100"
console.log("After discount: $"+discountedPrice);// "After discount: $80"
// 9: WHEN TO USE EACH STYLE