Understanding 'this' in JS V1
Himanshupal0001
Posted on June 12, 2024
The concept of 'this' keyword is one of the most confusing topics in JavaScript. Let's dig deep and understand the concept of 'this'.
But before starting anything we must clear some concepts to understand this concept better. This article is written considering beginners. Although I've seen many where even seniors don't know the underlying meaning of what they are writing. Before diving deep into the concept of 'this', I want that everyone on the same page and can understand every line of the code.
Table Of Content
- Difference between methods and functions
- Assigning values vs reference to variable
- Difference in function declaration, statement and expression
- Different ways to add a function as a property to an object
- Difference between fn() vs fn.
- What and Why 'this'
🌟Difference between method and a function
A function
is a self explanatory set of instructions wrapped inside a variable who's type is given by special keyword 'function'. Basically a function is just a set of instructions of lines that developer want to execute and than you wrap it around a variable to make it reusable and can use in different parts of the code.
On the other hand, methods
are just functions but they are part of an object. A method either can be implicitly defined in an object as a property of that object or a function explicitly can be assigned to an object as a property.
//Example of a function
function sum(a, b){
console.log(a+b);
}
sum(2,2); // function call
//Example of a method
const obj = {
name: 'John',
age:26,
sum(a,b){
console.log(a+b)
}
}
obj.sum(2,2) // accessing function from obj and calling it
/*
Different ways to define a function in a object
//anonymous function
const obj = {
name: 'John',
age:26,
sum: function(a,b){
console.log(a+b)
}
}
//arrowfunction
const obj = {
name: 'John',
age:26,
sum: (a,b) => {
console.log(a+b)
}
}
*/
🌟Assigning values vs reference to variable
It is crucial to understand the value vs reference type. For simplicity just understand all primitive values are assign by value
and a collection of primitive
are stored in objects which is non primitive are assign by reference.
Example of Primitive assignment to a variable
A primitive value which are absolute values like number and strings are stored directly into the variable.
let a = 10;
let b = a
b =20
console.log(a,b) // output=> 10, 20
Behind the scene, primitive values are assign like this
Example of Non-Primitive assignment to a variable
A non-primitve value which is an object, function or array has there own memory space and when assign to a variable, that variable just hold the address location of that literal.
//array literal => [1,2,3]
//The array literal has its own memory
const arr1 = [1,2,4];
const arr2 = arr1;
arr2.push(3);
console.log(arr1, arr2);
Behind the scene, non - primitive values are assign like this
Thus, a reference/copy of address just being assigned to a variable and if that address assign to another variable it doesn't change the fact that the address is same.
🌟Difference in function declaration, statement and expression
There are different ways to write a function. In programming world different jargons are used to style those functions writing and it is important to understand those jargons/style and how they impact on the code functionality.
Function declaration/statement
Function declaration or statement essentially the same. When a special keyword function
is used with the function name to define a function that is a function declaration or statement.
//below is the function declaration/statement
function sum(a,b){
console.log(a+b);
}
Function Expression
A function expression is nothing but a block of code assign to a variable and the whole logic boils down to a value which is assigned to that variable. Normally a function expression is a anonymous function with or without function keyword.
//Example of function expression
const sum = () => { console.log(a+b); }
//Another Example of function expression
const sum = function(){console.log(a+b);}
🌟Different ways to add a function as a property to an object
In an object there are two ways to add a function as a property to an object.
*Implicit method *
The the implicit methods are methods which are defined within the object.
const obj = {
name: 'John',
age:26,
sum(a,b){
console.log(a+b)
}
}
obj.sum(2,2)
*Explicit method *
Explicit methods are methods and when a function statement is assign to an object explicitly. It can be done in two ways.
Runtime method declaration
const obj = {
name: 'John',
age:26,
}
obj.sum = function(a,b){
console.log(a+b);
}
obj.sum(2,2); //function call
Pre-declare method
const obj = {
name: 'John',
age:26,
}
function sum(a,b){
console.log(a+b);
}
obj.sum = sum; // assigning function definition to object property 'sum'
obj.sum(2,2); //function call
🌟Difference between fn() vs fn.
This is crucial to know the what is the difference between fn() can fn. A fn
contains the actual body of the function while a fn()
is the invokation/call of that function. When a function is called the control goes to that function block.
function print(){
console.log('print this string');
}
console.log(print) // this will console log the body of the function within {}.
console.log(print())
or just
print() // will print the string 'print this string'
🌟 What and Why 'this'
Now the question is what is 'this' and why?
'this' keyword is a special keyword in JavaScript and almost all OOPS language it's the same. The main job of the 'this' keyword to provide context.
Now the question might arise context of what?
'this' provide context of the scope in which a function is calling. It provides accessibility of that object with which it attached to. In Javascript 'this' default refers to 'window' object in browser and GlobalThis in node js.
Because of 'this' we can access functions and methods already provided by the web Apis.
But for our use case we create functions and classes to add a particular functionality and we need to tell compiler during execution of the code which context we are talking about when executing a function. Because this binding in javascript happens during runtime.
I know to understand 'this' can be complicated. We'll deep dive in next article and understand how this works using code snippets.
Posted on June 12, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.