-
Notifications
You must be signed in to change notification settings - Fork 0
/
027-IIFE-Function.js
100 lines (81 loc) · 2.3 KB
/
027-IIFE-Function.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
/*
author : Jaydatt Patel
IIFE (Immediately Invoked Function Expression )
You can crete anonymous private function and can use to execute function directly without giving name or variable and it is defined in brakets. It can not access outside.
syntax:
(function() {}
)()
*/
console.log("------------1-------------");
(function () {
console.log("IIFE function");
})();
console.log("------------2-------------");
(function (a, b) {
console.log(a ** b);
})(4, 2);
console.log("------------3-------------");
const user = //creating IIFE private function that can not access outside.
(function () {
const userData = {
userName: "John",
userAge: 20,
};
function getName() {
console.log(userData.userName);
}
function updateAge(age) {
console.log(userData.userAge + age);
}
return { getName, updateAge };
})();
console.log(user);
console.log(user.userData);
user.getName();
user.updateAge(3);
console.log("------------4-------------");
var counter = (function () {
var count = 0;
return {
increment: function () {
count++;
},
getCount: function () {
return count;
},
};
})();
counter.increment();
counter.increment();
console.log(counter.getCount());
console.log("------------5-------------");
function main() {
const userAuth = (function () {
let users = [];
function checkCredentials(username, password) {
let flag = false;
for (let obj of users) {
if (obj["username"] === username) flag = true;
}
return flag;
}
function registerUser(username, password) {
if (checkCredentials(username, password)) {
return `The user is already registered`;
}
users.push({ username: username, password: password });
return `The user have been added to the registeredUser array`;
}
function show() {
console.log(users);
// for(let obj of users)
// console.log(obj['username'], obj['password'])
}
return { registerUser, checkCredentials, show };
})();
console.log(userAuth.registerUser("user1", "password123"));
console.log(userAuth.registerUser("user1", "password123"));
userAuth.show();
return userAuth;
}
main(); //calling main