1656648650
In this tutorial, we will talk about execution context and hoisting
Timestamps
0:00 - Intro
0:44 - What Is Execution Context?
1:39 - The 2 Phases
3:32 - Step By Step Examination
6:12 - Examine Creation In Browser
7:32 - Step-Through Execution
8:52 - Hoisting
11:26 - var vs let & const
JavaScript is an easy-to-learn programming language compared to many of its counterparts. However, a few basic concepts need a bit more attention if you want to understand, debug, and write better code.
In this article, we will learn about two such concepts,
As a beginner to JavaScript, understanding these concepts will help you understand the this
keyword, scope
, and closure
much more comfortably. So enjoy, and keep reading.
Execution Context in JavaScript
In general, a JavaScript source file will have multiple lines of code. As developers, we organize the code into variables, functions, data structures like objects and arrays, and more.
A Lexical Environment
determines how and where we write our code physically. Take a look at the code below:
function doSomething() {
var age= 7;
// Some more code
}
In the above code, the variable age
is lexically inside the function doSomething
.
Please note that our code does not run as-is. It has to be translated by the compiler into computer understandable byte-code. So the compiler needs to map what is lexically placed where in the meaningful and valid way.
Usually, there will be more than one Lexical Environment
in your code. However, not all the environments get executed at once.
The environment that helps the code get executed is called the Execution Context
. It is the code that's currently running, and everything surrounding that helps to run it.
There can be lots of Lexical Environment
s available, but the one currently running code is managed by the Execution Context
.
Check out the image below to understand the difference between a Lexical Environment and Execution Context:
Lexical Environment vs Execution Context
So what exactly happens in the Execution Context? The code gets parsed line-by-line, generates executable byte-code, allocates memory, and executes.
Let's take the same function we have seen above. What do you think may happen when the following line gets executed?
var age = 7;
There are many things happening behind the scenes. That piece of source code goes through the following phases before it is finally gets executed:
Tokens
. For example, the code var age = 7;
tokenizes into var, age, =, 7 and, ;.AST
(Abstract Syntax Tree).The animated picture below shows the transition of the source code to executable byte-code.
Source Code to Executable Byte-Code
All these things happen in an Execution Context
. So the execution context is the environment where a specific portion of the code executes.
There are two types of execution contexts:
And each of the execution contexts has two phases:
Let's take a detailed look at each of them and understand them a bit better.
Whenever we execute JavaScript code, it creates a Global Execution Context (also knows as Base Execution Context). The global execution context has two phases.
In the creation phase, two unique things get created:
window
(for the client-side JavaScript).this
.If there are any variables declared in the code, the memory gets allocated for the variable. The variable gets initialized with a unique value called undefined
. If there is a function
in the code, it gets placed directly into the memory. We will learn more about this part in the Hoisting
section later.
The code execution starts in this phase. Here, the value assignment of the global variables takes place. Please note that no function gets invoked here as it happens in the Function Execution Context. We will see that in a while.
Let's understand both the phases with a couple of examples.
Create an empty JavaScript file with the name index.js
. Now create an HTML file with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src='./index.js'></script>
</head>
<body>
I'm loading an empty script
</body>
</html>
Note that we are importing the empty script file into the HTML file using the <script>
tag.
Load the HTML file in the browser and open Chrome DevTools (usually using the F12
key) or equivalent for other browsers. Browse to the console
tab, type window
, and press enter. You should see the value as the browser's Window
object.
The Window object
Now, type the word this
and press enter. You should see the same Window
object value printed in the browser console.
Value of 'this'
Great, now try to check if window is equal to this
. Yes, it is.
window is equal to 'this'
Alright, so what have we learned?
window
object and this
.window
object and this
are equal.Let's now see an example with some code in the JavaScript file. We'll add a variable (blog) with a value assigned to it. We'll also define a function with the name logBlog
.
var blog = 'freeCodeCamp';
function logBlog() {
console.log(this.blog);
}
In the creation phase:
window
and the variable this
get created.blog
and the function logBlog
.blog
gets initialized by a special value undefined
. The function logBlog
gets placed in the memory directly.In the execution phase:
freeCodeCamp
is assigned to the variable blog
.When we invoke a function, a Function Execution Context gets created. Let's extend the same example we used above, but this time we will call the function.
var blog = 'freeCodeCamp';
function logBlog() {
console.log(this.blog);
}
// Let us call the function
logBlog();
The function execution context goes through the same phases, creation and execution.
The function execution phase has access to a special value called arguments
. It is the arguments passed to the function. In our example, there are no arguments passed.
Please note that the window
object and the this
variable created in the Global Execution Context are still accessible in this context.
When a function invokes another function, a new function execution context gets created for the new function call. Each of the function execution contexts determines the scope
of the variables used in the respective functions.
Hoisting in JavaScript
I hope you enjoyed learning about Execution Context
. Let's move over to another fundamental concept called Hoisting
. When I first heard about hoisting, it took some time to realize something seriously wrong with the name Hoisting
.
In the English language, hoisting means raising something using ropes and pulleys. The name may mislead you to think that the JavaScript engine pulls the variables and functions up at a specific code execution phase. Well, this isn't what happens.
So let's understand Hoisting
using the concept of the Execution Context
.
Please have a look at the example below and guess the output:
console.log(name);
var name;
I'm sure you guessed it already. It's the following:
undefined
However, the question is why? Suppose we use similar code in some other programming language. In that case, we may get an error saying the variable name
is not declared, and we are trying to access it well before that. The answer lies in the execution context.
In the creation
phase,
name
, andundefined
is assigned to the variable.In the execution
phase,
console.log(name)
statement will execute.This mechanism of allocating memory for variables and initializing with the value undefined
at the execution context's creation phase is called Variable Hoisting
.
The special value
undefined
means that a variable is declared but no value is assigned.
If we assign the variable a value like this:
name = 'freeCodeCamp';
The execution phase will assign this value to the variable.
Now let's talk about Function Hoisting
. It follows the same pattern as Variable Hoisting
.
The creation phase of the execution context puts the function declaration into the memory, and the execution phase executes it. Please have a look at the example below:
// Invoke the function functionA
functionA();
// Declare the function functionA
function functionA() {
console.log('Function A');
// Invoke the function FunctionB
functionB();
}
// Declare the function FunctionB
function functionB() {
console.log('Function B');
}
The output is the following:
Function A
Function B
functionA
in it.functionB
as well.Putting the entire function declaration ahead into the memory at the creation phase is called Function Hoisting
.
Since we understand the concept of Hoisting
now, let's understand a few ground rules:
logMe();
var logMe = function() {
console.log('Logging...');
}
The code execution will break because with function initialization, the variable logMe
will be hoisted as a variable, not as function. So with variable hoisting, memory allocation will happen with the initialization with undefined
. That's the reason we will get the error:
Error in hoisting a function initialization
Suppose we try to access a variable ahead of declaration and use the let
and const
keywords to declare it later. In that case, they will be hoisted but not assigned with the default undefined
. Accessing such variables will result in the ReferenceError
. Here is an example:
console.log(name);
let name;
It will throw the error:
Error with hoisting variable declared with let and const keywords
The same code will run without a problem if we use var
instead of let
and const
. This error is a safeguard mechanism from the JavaScript language as we have discussed already, as accidental hoisting may cause unnecessary troubles.
#javascript #programming
1639778400
PySQL is database framework for Python (v3.x) Language, Which is based on Python module mysql.connector, this module can help you to make your code more short and more easier. Before using this framework you must have knowledge about list, tuple, set, dictionary because all codes are designed using it. It's totally free and open source.
Before we said that this framework is based on mysql.connector so you have to install mysql.connector first on your system. Then you can import pysql and enjoy coding!
python -m pip install mysql-connector-python
After Install mysql.connector successfully create Python file download/install pysql on the same dir where you want to create program. You can clone is using git or npm command, and you can also downlaod manually from repository site.
Go to https://pypi.org/project/pysql-framework/ or use command
pip install pysql-framework
git clone https://github.com/rohit-chouhan/pysql
Go to https://www.npmjs.com/package/pysql or use command
$ npm i pysql
Install From Here https://marketplace.visualstudio.com/items?itemName=rohit-chouhan.pysql
Table of contents
To connect a database with localhost server or phpmyadmin, use connect method to establish your python with database server.
import pysql
db = pysql.connect(
"host",
"username",
"password"
)
Creating database in server, to use this method
import pysql
db = pysql.connect(
"host",
"username",
"password"
)
pysql.createDb(db,"demo")
#execute: CREATE DATABASE demo
To drop database use this method .
Syntex Code -
pysql.dropDb([connect_obj,"table_name"])
Example Code -
pysql.dropDb([db,"demo"])
#execute:DROP DATABASE demo
To connect a database with localhost server or phpmyadmin, use connect method to establish your python with database server.
import pysql
db = pysql.connect(
"host",
"username",
"password",
"database"
)
To create table in database use this method to pass column name as key and data type as value.
Syntex Code -
pysql.createTable([db,"table_name_to_create"],{
"column_name":"data_type",
"column_name":"data_type"
})
Example Code -
pysql.createTable([db,"details"],{
"id":"int(11) primary",
"name":"text",
"email":"varchar(50)",
"address":"varchar(500)"
})
2nd Example Code -
Use can use any Constraint with Data Value
pysql.createTable([db,"details"],{
"id":"int NOT NULL PRIMARY KEY",
"name":"varchar(20) NOT NULL",
"email":"varchar(50)",
"address":"varchar(500)"
})
To drop table in database use this method .
Syntex Code -
pysql.dropTable([connect_obj,"table_name"])
Example Code -
pysql.dropTable([db,"users"])
#execute:DROP TABLE users
For Select data from table, you have to mention the connector object with table name. pass column names in set.
Syntex For All Data (*)
-
records = pysql.selectAll([db,"table_name"])
for x in records:
print(x)
Example - -
records = pysql.selectAll([db,"details"])
for x in records:
print(x)
#execute: SELECT * FROM details
Syntex For Specific Column
-
records = pysql.select([db,"table_name"],{"column","column"})
for x in records:
print(x)
Example - -
records = pysql.select([db,"details"],{"name","email"})
for x in records:
print(x)
#execute: SELECT name, email FROM details
Syntex Where and Where Not
-
#For Where Column=Data
records = pysql.selectWhere([db,"table_name"],{"column","column"},("column","data"))
#For Where Not Column=Data (use ! with column)
records = pysql.selectWhere([db,"table_name"],{"column","column"},("column!","data"))
for x in records:
print(x)
Example - -
records = pysql.selectWhere([db,"details"],{"name","email"},("county","india"))
for x in records:
print(x)
#execute: SELECT name, email FROM details WHERE country='india'
To add column in table, use this method to pass column name as key and data type as value. Note: you can only add one column only one call
Syntex Code -
pysql.addColumn([db,"table_name"],{
"column_name":"data_type"
})
Example Code -
pysql.addColumn([db,"details"],{
"email":"varchar(50)"
})
#execute: ALTER TABLE details ADD email varchar(50);
To modify data type of column table, use this method to pass column name as key and data type as value.
Syntex Code -
pysql.modifyColumn([db,"table_name"],{
"column_name":"new_data_type"
})
Example Code -
pysql.modifyColumn([db,"details"],{
"email":"text"
})
#execute: ALTER TABLE details MODIFY COLUMN email text;
Note: you can only add one column only one call
Syntex Code -
pysql.dropColumn([db,"table_name"],"column_name")
Example Code -
pysql.dropColumn([db,"details"],"name")
#execute: ALTER TABLE details DROP COLUMN name
To execute manual SQL Query to use this method.
Syntex Code -
pysql.query(connector_object,your_query)
Example Code -
pysql.query(db,"INSERT INTO users (name) VALUES ('Rohit')")
For Inserting data in database, you have to mention the connector object with table name, and data as sets.
Syntex -
data = {
"db_column":"Data for Insert",
"db_column":"Data for Insert"
}
pysql.insert([db,"table_name"],data)
Example Code -
data = {
"name":"Komal Sharma",
"contry":"India"
}
pysql.insert([db,"users"],data)
For Update data in database, you have to mention the connector object with table name, and data as tuple.
Syntex For Updating All Data
-
data = ("column","data to update")
pysql.updateAll([db,"users"],data)
Example - -
data = ("name","Rohit")
pysql.updateAll([db,"users"],data)
#execute: UPDATE users SET name='Rohit'
Syntex For Updating Data (Where and Where Not)
-
data = ("column","data to update")
#For Where Column=Data
where = ("column","data")
#For Where Not Column=Data (use ! with column)
where = ("column!","data")
pysql.update([db,"users"],data,where)
Example -
data = ("name","Rohit")
where = ("id",1)
pysql.update([db,"users"],data,where)
#execute: UPDATE users SET name='Rohit' WHERE id=1
For Delete data in database, you have to mention the connector object with table name.
Syntex For Delete All Data
-
pysql.deleteAll([db,"table_name"])
Example - -
pysql.deleteAll([db,"users"])
#execute: DELETE FROM users
Syntex For Deleting Data (Where and Where Not)
-
where = ("column","data")
pysql.delete([db,"table_name"],where)
Example -
#For Where Column=Data
where = ("id",1)
#For Where Not Column=Data (use ! with column)
where = ("id!",1)
pysql.delete([db,"users"],where)
#execute: DELETE FROM users WHERE id=1
[19/06/2021]
- ConnectSever() removed and merged to Connect()
- deleteAll() [Fixed]
- dropTable() [Added]
- dropDb() [Added]
[20/06/2021]
- Where Not Docs [Added]
The module is designed by Rohit Chouhan, contact us for any bug report, feature or business inquiry.
Author: rohit-chouhan
Source Code: https://github.com/rohit-chouhan/pysql
License: Apache-2.0 License
1599539040
In JavaScript, Hoisting is the default behavior where variables and function declarations are moved to the top of their scope before code execution.
No Matter where function and variable are declared, it moved up top on their own scope. Doing this, it allows us to call functions before even writing them in our code.
How interpreter sees the above code:
We Know, In JavaScript, when we have a variable that is not defined then it occurs an undefined error. So in the above example, JavaScript only hoists the declarations part and we got an undefined error.
It’s important to keep in mind that, JavaScript only hoists declarations, not the initializations.
let us take another example,
why this time we got a ReferenceError? Because of trying to access a previously undeclared variable And remember JavaScript only hoists declarations. So Initialisation can’t be hoisted and we got an error.
ES6: Let Keyword
Like before, for the var keyword, we expect the output to be undefined. But this time we got a reference error. That Means let and const variables not hoisted? The answer is Variables declared with let are still hoisted, but not initialized, inside their nearest enclosing block. If we try to access it before initializing will throw ReferenceError due being into Temporal Dead Zone.
Hoisting functions
Like variables, the JavaScript engine also hoists the function declarations. And it allows us to call functions before even writing them in our code.
#javascript-hoisting #understanding #js-hoisting #javascript #hoisting
1622207074
Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.
JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.
JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.
Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.
In JavaScript, ‘document.write‘ is used to represent a string on a browser.
<script type="text/javascript">
document.write("Hello World!");
</script>
<script type="text/javascript">
//single line comment
/* document.write("Hello"); */
</script>
#javascript #javascript code #javascript hello world #what is javascript #who invented javascript
1616670795
It is said that a digital resource a business has must be interactive in nature, so the website or the business app should be interactive. How do you make the app interactive? With the use of JavaScript.
Does your business need an interactive website or app?
Hire Dedicated JavaScript Developer from WebClues Infotech as the developer we offer is highly skilled and expert in what they do. Our developers are collaborative in nature and work with complete transparency with the customers.
The technology used to develop the overall app by the developers from WebClues Infotech is at par with the latest available technology.
Get your business app with JavaScript
For more inquiry click here https://bit.ly/31eZyDZ
Book Free Interview: https://bit.ly/3dDShFg
#hire dedicated javascript developers #hire javascript developers #top javascript developers for hire #hire javascript developer #hire a freelancer for javascript developer #hire the best javascript developers
1589255577
As a JavaScript developer of any level, you need to understand its foundational concepts and some of the new ideas that help us developing code. In this article, we are going to review 16 basic concepts. So without further ado, let’s get to it.
#javascript-interview #javascript-development #javascript-fundamental #javascript #javascript-tips