JavaScript Execution Context and Hoisting Explained with Examples

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 Execution Context and Hoisting Explained with Code Examples

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,

  • Execution Context
  • Hoisting

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 Environments 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

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:

  • Tokenizing: In this phase, the source code string breaks into multiple meaningful chunks called Tokens. For example, the code var age = 7; tokenizes into var, age, =, 7 and, ;.
  • Parsing: The next phase is parsing, where an array of tokens turns into a tree of nested elements understood by the language's grammar. This tree is called an AST (Abstract Syntax Tree).
  • Code Generation: In this phase, the AST created in the parsing phase turns into executable byte-code. This executable byte-code is then optimized further by the JIT (Just-In-Time) compiler.

The animated picture below shows the transition of the source code to executable byte-code.

execution_steps

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:

  • Global Execution Context (GEC)
  • Function Execution Context (FEC)

And each of the execution contexts has two phases:

  • Creation Phase
  • Execution Phase

Let's take a detailed look at each of them and understand them a bit better.

Global Execution Context (GEC) in JavaScript

Whenever we execute JavaScript code, it creates a Global Execution Context (also knows as Base Execution Context). The global execution context has two phases.

Creation Phase

In the creation phase, two unique things get created:

  • A global object called window (for the client-side JavaScript).
  • A global variable called 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.

Execution Phase

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.

Example 1: Load an Empty Script

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.

image-102

The Window object

Now, type the word this and press enter. You should see the same Window object value printed in the browser console.

image-103

Value of 'this'

Great, now try to check if window is equal to this. Yes, it is.

image-104

window is equal to 'this'

Alright, so what have we learned?

  • The Global Execution Context gets created when we load the JavaScript file, even when it is empty.
  • It creates two special things for us in its creation phase, that is the window object and this.
  • In Global Execution context, the window object and this are equal.
  • There is nothing to execute as the script file is blank. So nothing happens in the execution phase.

Example 2: With Variables and Functions

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:

  • The global object window and the variable this get created.
  • Memory gets allocated for the variable blog and the function logBlog.
  • The variable blog gets initialized by a special value undefined. The function logBlog gets placed in the memory directly.

In the execution phase:

  • The value freeCodeCamp is assigned to the variable blog.
  • As we have defined the function but not called it yet, the function execution does not take place. We will call the function and see what happens when we learn about the Function Execution Context.

Function Execution Context (FEC) in JavaScript

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.

Variable Hoisting in JavaScript

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,

  • The memory gets allocated for the variable name, and
  • A special value undefined is assigned to the variable.

In the execution phase,

  • The 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.

Function Hoisting in JavaScript

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
  • The execution context creates the memory for the function and puts the entire function declaration of functionA in it.
  • The functions create their own execution context. So a similar thing happens for functionB as well.
  • Next, the functions get executed in their execution context respectively.

Putting the entire function declaration ahead into the memory at the creation phase is called Function Hoisting.

A Few Ground Rules

Since we understand the concept of Hoisting now, let's understand a few ground rules:

  • Always define variables and functions before using them in your code. It reduces the chances of surprise errors and debugging nightmares.
  • Hoisting is only for function declaration, not initialization. Here is an example of function initialization where the code execution will break.
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:

image-105

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:

image-106

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 

What is GEEK

Buddha Community

JavaScript Execution Context and Hoisting Explained with Examples
Grace  Lesch

Grace Lesch

1639778400

PySQL Tutorial: A Database Framework for Python

PySQL 

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.

Tutorial Video in English (Watch Now)

IMAGE ALT TEXT HERE

Installation

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.

PyPi Command

Go to https://pypi.org/project/pysql-framework/ or use command

pip install pysql-framework

Git Command

git clone https://github.com/rohit-chouhan/pysql

Npm Command

Go to https://www.npmjs.com/package/pysql or use command

$ npm i pysql

Snippet Extention for VS Code

Install From Here https://marketplace.visualstudio.com/items?itemName=rohit-chouhan.pysql

IMAGE ALT TEXT HERE

Table of contents

Connecting a Server


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"
 )

Create a Database in Server


Creating database in server, to use this method

import pysql

db = pysql.connect(
    "host",
    "username",
    "password"
 )
 pysql.createDb(db,"demo")
 #execute: CREATE DATABASE demo

Drop Database


To drop database use this method .

Syntex Code -

pysql.dropDb([connect_obj,"table_name"])

Example Code -

pysql.dropDb([db,"demo"])
#execute:DROP DATABASE demo

Connecting a Database


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"
 )

Creating Table in 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)"
})

Drop Table in Database


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

Selecting data from Table


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'

Add New Column to Table


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);

Modify Column to Table


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;

Drop Column from Table


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

Manual Execute Query


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')")

Inserting data


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)

Updating 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

Deleting data


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

--- Finish ---

Change Logs

[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

#python 

Understanding Hoisting in JavaScript

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.

Image for post

How interpreter sees the above code:

Image for post

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,

Image for post

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

Image for post

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

Rahul Jangid

1622207074

What is JavaScript - Stackfindover - Blog

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.

Who invented JavaScript?

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.

What is JavaScript?

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.

JavaScript Hello World Program

In JavaScript, ‘document.write‘ is used to represent a string on a browser.

<script type="text/javascript">
	document.write("Hello World!");
</script>

How to comment JavaScript code?

  • For single line comment in JavaScript we have to use // (double slashes)
  • For multiple line comments we have to use / * – – * /
<script type="text/javascript">

//single line comment

/* document.write("Hello"); */

</script>

Advantages and Disadvantages of JavaScript

#javascript #javascript code #javascript hello world #what is javascript #who invented javascript

Hire Dedicated JavaScript Developers -Hire JavaScript Developers

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

Niraj Kafle

1589255577

The essential JavaScript concepts that you should understand

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