Skip to content

Commit 1c1e996

Browse files
committed
Learned about "This" keyword, where "This" keyword works & also about Arrow functions and it's explicit and implicit return.
1 parent efe0061 commit 1c1e996

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

03_Basics/05_arrow.js

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
// 5. This
2+
3+
const user = {
4+
username: "Ayush",
5+
price: 999,
6+
welcomeMessage: function (){
7+
console.log(`${this.username}, welcome to website.`);
8+
// Note: While referring current context we use 'this' keyword.
9+
console.log(this); // Note: Will print the current context.
10+
}
11+
}
12+
// user.welcomeMessage() // Output: Ayush, welcome to website.
13+
// user.username = "sam"
14+
// user.welcomeMessage() // Output: sam, welcome to website.
15+
16+
console.log(this); // Output: {} Prints an empty object.
17+
// Note: When we run this in browser's console we get window global object.
18+
19+
function one(){
20+
console.log(this);
21+
}
22+
// one() // Output: We get many values
23+
24+
function two() {
25+
let username = "ayush"
26+
console.log(this.username);
27+
}
28+
// two() // Output: Undefined
29+
30+
const three = function (){
31+
let username = "sam"
32+
console.log(this.username);
33+
}
34+
// three() // Output: undefined
35+
36+
/* ---------------------------------------------------------------------------
37+
Arrow Function, */
38+
39+
const chai = () => { // It's an arrow function
40+
let name = "Ayush"
41+
console.log(this.username);
42+
}
43+
chai() // Output: undefined
44+
// Note: If in arrow function we do console.log(this) then we get empty {}
45+
46+
// Explicit Return
47+
const addTwo = (num1, num2) => {
48+
return num1 + num2
49+
}
50+
console.log(addTwo(3, 4)) // Output: 7
51+
52+
// Implicit Return,
53+
const add = (num1, num2) => (num1 + num2)
54+
console.log(add(3, 4)); // Output: 7
55+
56+
/* Note: When using curly braces {} then we have use return keyword and when
57+
using parenthesis () then we don't have to use return keyword. */
58+
59+
const returnObject = () => ({username: "ayush"})
60+
console.log(returnObject()) // Output: { username: 'ayush' }

0 commit comments

Comments
 (0)