How Javascript is working-Mechanisms
Contents
- Create a JavaScript variable
- Create a JavaScript function
- Assign JavaScript function as a variable
- Create a JSON Object
- Understand about the scope and get the idea about the “this” keyword
- The difference between bind and call
- How to create a JavaScript class and way of using the prototype
- What is closure and behavior of closure
Create a JavaScript variable
There are no variable types like int, String in JavaScript. The way that creating JavaScript variables is given below.
There are three keywords used when declaring a variable in Javascript, namely, var, let and const.
var age=15;
let age=15;
cons age=15;
There are three keywords used when declaring a variable in Javascript, namely, var, let and const.
var age=15;
let age=15;
cons age=15;
var Method
This was the only way to declare a variable before ES6. Here you can declare the same variables more than one time and can be updated.
This was the only way to declare a variable before ES6. Here you can declare the same variables more than one time and can be updated.
var myFriend = 'Kevin';
var myFriend = 'Dayana';
console.log(myFriend); // 'Dayana'
If you declare variable inside the block statement, the variable will leak outside.
var bodyWeight = 50;
if (bodyWeight > 49) {
var water = 1.4;
console.log(`For body weight of ${bodyWeight}kg, you should drink water atleast ${water}litre`);
}
console.log(water); // 1.4
let and const Method
let and const are the new ways for declaring variables introduced in ES6. Within let and const you cannot declare the variable twice.
let myFriend = 'Kevin';
let myFriend = 'Dayana'; // Uncaught SyntaxError: Identifier 'myFriend' has already been declared
In most case let and const are almost the same, the only difference I know is, const cannot be updated but let can be updated.
// let can be updated
let myFriend = 'Jhon';
myFriend = 'Kevin';
console.log(myFriend); // Kevin
// const cannot be updated
const otherFriend = 'Monica';
otherFriend = 'Raphael'; // Uncaught TypeError: Assignment to constant variable.
The variable won't be leaked outside of the block statement if you use let or const.
And this is another way of explaining about the const variables.
<script type="text/javascript">
const person = {
first_name: "Kevin",
last_name: "Marshal",
Age: 25,
About: "Web Developer"
};
console.log(person);
// It is possible
person.first_name = "Jhon";
person.last_name = "Alaxan";
person.Age = 22;
person.About = "SE Undergraduate";
console.log(person);
// it is not possible
// const person={
// "first_name":"Aryan",
// "last_name":"Yadav",
// "Age":22,
// "About":"Commerce undergraduate"
// }
</script>
Output:
It describes that the object properties can be modified the only reference to an object cannot be changed.
Create a JavaScript Function
A function is a set of statements that take inputs, do some specific computation and produces output. Basically, a function is a set of statements that performs some tasks or does some computation and then returns the result to the user.
The idea is to put some commonly or repeatedly done task together and make a function so that instead of writing the same code again and again for different inputs, we can call that function.
function calcAddition(number1, number2)
{
return number1 + number2;
}
calcAddition(2,3); //Calling the Function
Create a JSON object
What is JSON
JSON or JavaScript Object Notation is a format for structuring data
What is it used for?
Like XML, it is one of the ways of formatting the data. Such a format of data is used by web applications to communicate with each other.
Characteristics of JSON
It is Human-readable and writable.
It is a lightweight text-based data interchange format which means, it is simpler to read and write when compared to XML.
var person=
{
"name": "Thanos",
"occupation": "Developer",
"hobbies":
["coding","developing website"
"listening to music", ""]
}
Here the "person" is the object and "hobbies" is an array
Understand the scope and get the idea of the “this” keyword
Understanding this is absolutely vital in order to understand more advanced concepts in JavaScript or to read and write JavaScript code, which is why I shall spend this article trying to clarify what this really means in JavaScript.
The value that "this" store is the current execution context of the JavaScript program. Thus, when used inside a function this's value will change depending on how that function is defined, how it is invoked and the default execution context.
"this" with method invocation:
Functions, when defined as fields or properties of objects, are referred to as methods
John is 31 years old
bind():
bind() allows us to explicitly define what value this will have inside a function by binding an object to that function.
The bound object serves as the context(this value) for the function that it was bound to.
To use it, we need primarily two things – An object to bind to a function and a function that this object is to be bound to.
<html>
<body>
<script>
let fruit = function(food, color) {
this.food = food;
this.color = color;
this.displayInfo = function() {
document.write(this.food + " is " + this.color + '<br>');
}
}
let bindingObj
= {
// creating an object using object literal syntax
food : "Banana",
color : "Yellow",
}
// Constructor invocation to create an object fruit1
let fruit1
= new fruit("Orange", "orange");
// logs :Orange is orange
// Method invocation of displayInfo()
fruit1.displayInfo();
// binding the separated method to a new object
let newBound = fruit1.displayInfo.bind(bindingObj);
// logs : Banana is Yellow
newBound();
</script>
</body>
</html>
Output:
Orange is orange
Banana is Yellow
Notice that we call displayInfo() on fruit1 using method invocation: fruit1.displayInfo and therefore might expect it to have the context of fruit1. However, this does not seem to be the case as “Banana is Yellow” gets logged instead of “Orange is orange”.
This happens because we explicitly bind the value of this inside displayInfo() using the bind() command to bindingObj.
As we can see, binding an object explicitly to a function overrides its normal context rules and forcefully sets all "this" values to the bound object inside it.
call():
call() performs a task similar to bind by explicitly specifying what value this should store inside a function
<html>
<body>
<script>
// Create two different objects to test call() and apply()
let banana = { food: 'Banana' };
let orange = { food: 'Orange' };
function fruits(adj)
{
document.write(this + ' ');
return (this.person + " is " + adj + '<br>');
}
// call() and apply() will immediately invoke
// the function they are being called on
// logs : Banana is yummy
document.write(fruits.call(banana, 'yummy'));
</script>
</body>
</html>
Output:
[object Object] Banana is yummy
[object Object] Orange is sour
Object Prototypes
JavaScript prototypes are used for accessing properties and methods of objects.
The prototypes may be used to add new properties and methods to the existing objects and object constructor.
This shows adding a new property to the object
<html>
<head>
<title>
JavaScript Object Prototypes
</title>
</head>
<body>
<p id="abc"></p>
<script>
function Student(a, b) {
this.name = a;
this.id = b;
}
Student.prototype.age = 12;
var s1 = new Student("Anju", 1234567);
document.getElementById("abc").innerHTML = s1.name +
" is " + s1.age + " years old.";
</script>
</body>
</html>
Output:
Anju is 12 years old.
Closure
Definition of Closure:
In programming languages, closures (also lexical closures or function closures) are techniques for implementing lexically scoped name binding in languages with first-class functions. Operationally, a closure is a record storing a function[a] together with an environment:[1] a mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or reference to which the name was bound when the closure was created.[b]
-Wikipedia-
-Wikipedia-
or
In other words, closure is created when a child function keep the environment of the parent scope even after the parent function has already executed
In other words, closure is created when a child function keep the environment of the parent scope even after the parent function has already executed
knowing closure will provide better control over the code when using them.
Explanation of closure
/* 1 */ function foo()
/* 2 */ {
/* 3 */ var b = 1;
/* 4 */ function inner(){
/* 5 */ return b;
/* 6 */ }
/* 7 */ return n;
/* 8 */ }
/* 9 */ var get_func_inner = foo();
/* 10 */ console.log(get_func_n());
/* 11 */ console.log(get_func_n());
/* 12 */ console.log(get_func_n());
The interesting thing to note here is from line number 9 to line number 12. At line number 9 we are done with the execution of function foo() but we can access the variable b which is defined in function foo() through function inner() i.e in line number 10, 11, 12. and as desired it logs the value of b. This is closure in action that is inner function can have access to the outer function variables as well as all the global variables.
The output of the above code:
1
1
1
Comments
Post a Comment