LogicanDx
  • Home
  • Blog
  • About Us
  • Contact
  • Categories
    • Advance Javascript
    • Javascript
    • Reactjs
    • Nodejs
    • Interview Related Questions

 

How Javascript Works in Browser And How DOM Works In Web Browser

No Comments
admin
March 4, 2023

How Javascript Works In Web Browser

Introduction: JavaScript is a popular programming language used for creating interactive websites and web applications. It is a client-side language, which means that it runs on the user’s computer within a web browser. In this article, we will explore how JavaScript works in the browser.

  1. Parsing: The first step in the process of running JavaScript in the browser is parsing. When a web page is loaded in the browser, the HTML, CSS, and JavaScript code is parsed and converted into a Document Object Model (DOM) tree, a Cascading Style Sheets (CSS) Object Model tree, and a JavaScript Object Model (JSOM) tree respectively.

The DOM tree represents the HTML content of the web page, the CSSOM tree represents the styles applied to the HTML elements, and the JSOM tree represents the JavaScript code of the web page.

  1. Execution: After the JavaScript code is parsed and converted into a JSOM tree, the browser starts executing the code. The execution process is carried out by the JavaScript engine, which is a component of the browser that interprets and executes the JavaScript code.

The JavaScript engine reads the JavaScript code from the JSOM tree and executes it line by line. It also creates and manages the execution context, which includes the scope chain, variable environment, and the this keyword.

  1. Event Loop: JavaScript is an event-driven language, which means that it responds to events such as user interactions and network requests. When an event occurs, the JavaScript engine adds the event to the event queue and continues executing the current code.

The event loop is a mechanism that allows the JavaScript engine to process events from the event queue. It checks the event queue for new events and executes them in the order they were added to the queue.

  1. Manipulating the DOM: One of the key features of JavaScript is its ability to manipulate the DOM. The DOM provides a structured representation of the HTML content of a web page, and JavaScript can be used to modify the content and style of the elements in the DOM.

JavaScript can be used to add, remove, or modify HTML elements, change the style of elements, and respond to user interactions such as mouse clicks and keyboard events.

  1. AJAX: JavaScript can also be used to make asynchronous requests to the server using the XMLHttpRequest object. This feature is known as AJAX (Asynchronous JavaScript and XML) and allows web pages to update content without reloading the entire page.

AJAX requests are sent using the XMLHttpRequest object, and the response is handled using callback functions. The response can be in various formats such as JSON, XML, or plain text.

Conclusion: JavaScript is an essential part of modern web development and plays a critical role in creating interactive and responsive web applications. Understanding how JavaScript works in the browser is essential for web developers to create efficient and effective web applications.

How DOM Works In Web Browser

Introduction: The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the structure of a web page as a tree-like structure of objects that can be manipulated using JavaScript. In this article, we will explore what DOM is and how it works in the browser.

What is DOM? The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the structure of a web page as a tree-like structure of objects that can be manipulated using JavaScript.

The DOM provides a structured representation of the HTML content of a web page. It consists of a tree of nodes, where each node represents an element, attribute, or text content of the web page.

How Does DOM Work in the Browser? When a web page is loaded in a browser, the browser parses the HTML code and converts it into a tree-like structure of objects called the DOM tree.

The DOM tree consists of three types of nodes:

  1. Element nodes: represent the HTML elements of the web page, such as <body>, <div>, <p>, etc.

  2. Attribute nodes: represent the attributes of the HTML elements, such as id, class, src, href, etc.

  3. Text nodes: represent the text content of the HTML elements.

Once the DOM tree is created, JavaScript can be used to manipulate the elements and attributes of the web page. For example, JavaScript can be used to add, remove, or modify HTML elements, change the style of elements, and respond to user interactions such as mouse clicks and keyboard events.

JavaScript can access the DOM tree using the Document object, which represents the root of the DOM tree. The Document object provides a range of methods and properties that can be used to manipulate the DOM.

For example, the Document object provides the following methods:

  1. getElementById(): returns the element with the specified ID.

  2. getElementsByClassName(): returns a collection of elements with the specified class name.

  3. getElementsByTagName(): returns a collection of elements with the specified tag name.

  4. createElement(): creates a new element node.

  5. appendChild(): adds a new child node to an element.

JavaScript can also be used to add event listeners to the elements of the web page. An event listener is a function that is executed when a specific event occurs, such as a mouse click or a keyboard event.

Conclusion: The DOM is a critical component of modern web development and plays a crucial role in creating interactive and responsive web applications. Understanding how the DOM works in the browser is essential for web developers to create efficient and effective web applications. With JavaScript and the DOM, web developers can create dynamic and engaging web pages that respond to user interactions in real-time.

Read More

Feature of ES6 In Javacript

No Comments
admin
March 4, 2023

Features Of ES6 In Javascript

Introduction:
ES6, also known as ECMAScript 2015, is a major update to the JavaScript language that was released in 2015. It introduced a number of new features and improvements over previous versions of JavaScript. In this article, we will explore some of the key features of ES6.

  1. Let and Const Keywords:
    ES6 introduced two new keywords, let and const, for variable declarations. Unlike the var keyword, which is function-scoped, the let and const keywords are block-scoped. This means that variables declared with let and const are only accessible within the block in which they are defined.

The let keyword is used for variables that can be reassigned, while the const keyword is used for variables that cannot be reassigned. This helps to prevent accidental overwriting of variables and makes code more readable.

Example:

 

javascript

 

let x = 10; // x can be reassigned 
const y = 20; // y cannot be reassigned

 

 

  1. Arrow Functions:
    Arrow functions are a new way to define functions in ES6. They are shorter and more concise than traditional functions and provide a simpler syntax for defining functions.

Arrow functions also have a lexical this binding, which means that they inherit the this value from the surrounding code. This makes it easier to use them in object-oriented programming.

Example:

 

css

 

// ES5 Function var sum = function(a, b) { return a + b; } 
 // ES6 Arrow Function const sum = (a, b) => a + b;

 

 

  1. Template Literals:
    Template literals are a new way to define strings in ES6. They provide a simpler syntax for creating dynamic strings that contain variables or expressions.

Template literals are enclosed in backticks (`) instead of single or double quotes. Variables or expressions can be enclosed in ${} brackets within the template literal.

Example:

 

javascript

 

const name = 'John'; 
const age = 30; 
// ES5 String Concatenation var message = 'My name is ' + name + ' and I am ' + age + ' years old.'; 
// ES6 Template Literal const message = `My name is ${name} and I am ${age} years old.`;

 

 

  1. Classes:
    ES6 introduced the class syntax, which provides a simpler and more intuitive way to create objects and object-oriented code. Classes are essentially a syntactical sugar over the existing prototype-based inheritance.

Classes can define properties and methods, which can be inherited by subclasses using the extends keyword. Classes can also define constructors, which are used to initialize object instances.

Example:

 

javascript

 

class Person { 

 

constructor(name, age) { 

 

this.name = name; 

 

this.age = age; 

 

 } 

 

sayHello() { 

 

console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`); 

 

 } } 

 

class Student extends Person { 

 

constructor(name, age, major) { 

 

super(name, age); 

 

this.major = major; 

 

 } 

 

sayHello() { 

 

console.log(`Hello, my name is ${this.name} and I am ${this.age} years old. My major is ${this.major}.`); 

 

 } } 

 

const john = new Student('John', 20, 'Computer Science'); 

 

john.sayHello(); 

 

// Output: "Hello, my name is John and I am 20 years old. My major is Computer Science."

 

  1.  
  2. ES5:

function Person(name, age) { this.name = name; this.age = age; }

Person.prototype.sayName = function() { console.log(this.name); }

ES6: class Person { constructor(name, age) { this.name = name; this.age = age; }

sayName() { console.log(this.name); } }

  1. Default parameters: ES6 allows us to set default values for function parameters. This feature makes it easier to write functions that handle missing or undefined parameters.

ES5: function greet(name) { name = name || “World”; console.log(“Hello, ” + name + “!”); }

greet(); // Output: Hello, World! greet(“John”); // Output: Hello, John!

ES6: function greet(name = “World”) { console.log(Hello, ${name}!); }

greet(); // Output: Hello, World! greet(“John”); // Output: Hello, John!

Read More

Event Loop in Javacript

No Comments
admin
March 1, 2023

Event Loop in Javascript

JavaScript is a powerful language used for creating web applications. One of its unique features is its ability to handle asynchronous tasks through the use of an event loop. Understanding the event loop is crucial for writing efficient and performant JavaScript code. In this article, we will explore the event loop in JavaScript in detail.

What is the Event Loop?

The event loop is a mechanism in JavaScript that handles asynchronous tasks in the language. It is responsible for managing the execution of tasks that do not block the execution of the program. The event loop is an infinite loop that runs continuously in the background of the JavaScript runtime environment.

The event loop works by monitoring the execution stack of the JavaScript program. Whenever the execution stack is empty, the event loop checks the task queue for any pending tasks. If there are tasks in the queue, the event loop executes them one by one. This process continues until there are no more tasks in the queue, and the program terminates.

Tasks in the task queue can be either microtasks or macrotasks. Microtasks have a higher priority than macrotasks and are executed before macrotasks. We will explore this concept in more detail later in the article.

The event loop is a crucial component of JavaScript, and understanding how it works is essential for writing efficient and performant JavaScript code.

How Does the Event Loop Work?

To understand how the event loop works, we need to first understand the JavaScript runtime environment. The JavaScript runtime environment consists of two main components, the Call Stack and the Heap.

The Call Stack is a data structure that stores the execution context of the current running function. Whenever a function is called, its execution context is pushed onto the Call Stack. When the function returns, its execution context is popped from the Call Stack.

The Heap is a region of memory that stores objects created by the program. Objects in the Heap can be accessed by the program through variables and references.

When a JavaScript program is executed, the main thread of execution enters the event loop. The event loop continuously monitors the Call Stack for any pending function calls. If there are function calls pending in the Call Stack, the event loop waits for them to complete before checking the task queue for any pending tasks.

If there are no function calls pending in the Call Stack, the event loop checks the task queue for any pending tasks. If there are tasks in the task queue, the event loop executes them one by one. This process continues until there are no more tasks in the queue, and the program terminates.

Types of Tasks in the Task Queue

Tasks in the task queue can be either microtasks or macrotasks. Microtasks have a higher priority than macrotasks and are executed before macrotasks.

Microtasks are used for tasks that need to be executed immediately after the completion of the current task. For example, when a promise is resolved, its associated callback is executed as a microtask. Other examples of microtasks include mutation observer callbacks and process.nextTick in Node.js.

Macrotasks are used for tasks that can be deferred and executed later. For example, setTimeout and setInterval callbacks are executed as macrotasks. Other examples of macrotasks include I/O operations and DOM events.

It is important to note that the event loop prioritizes microtasks over macrotasks. This means that if there are microtasks and macrotasks in the task queue, the event loop will execute all microtasks before executing any macrotasks.

Example of the Event Loop in Action

Let’s look at an example to understand how the event loop works in JavaScript.

javascript
console.log('Start'); 
setTimeout(() => { 
console.log(‘setTimeout’); 
}, 0); 
Promise.resolve().then(() => { console.log(‘Promise’); });
console.log(‘End’);

In this example, we have

Read More

Memo In Javascript

No Comments
admin
March 1, 2023

Memo In Javascript

Memoization is a powerful technique used to optimize the performance of functions in many programming languages, including JavaScript. By caching the results of expensive function calls and returning the cached value whenever possible, memoization can greatly improve the performance of your application.

In this article, we will explore memoization in JavaScript in more detail, including how to implement memoization, how to use memoization to optimize your code, and some best practices for using memoization effectively.

What is Memoization?

Memoization is a technique used to optimize the performance of a function by caching the results of expensive function calls and returning the cached value whenever possible. This is achieved by storing the arguments of a function as a key in a cache object, and the corresponding output of the function as the value associated with that key. If the function is called again with the same arguments, the cached value is returned instead of recomputing the function.

Memoization is particularly useful for functions that perform expensive computations or I/O operations, such as network requests or database queries. By caching the results of these operations, memoization can greatly improve the performance of your application and reduce the amount of time spent waiting for data to be fetched.

How to Implement Memoization in JavaScript

In JavaScript, memoization can be implemented using a simple caching mechanism that stores the results of function calls in an object. Here is an example of a memoized function in JavaScript:

javascript
function memoize(func) { const cache = {}; return function(...args) { const key = JSON.stringify(args); if (key in cache) { return cache[key]; } else { const result = func.apply(this, args); cache[key] = result; return result; } } }

This function takes in a function as an argument, and returns a new function that has been memoized. The memoized function checks if the arguments passed to it are already in the cache object, and returns the cached value if they are. Otherwise, it computes the result using the original function, caches the result, and returns it.

Here’s an example of how to use the memoize function:

javascript
function expensiveComputation(n) { // Perform some expensive computation here return n * n; } const memoizedComputation = memoize(expensiveComputation); console.log(memoizedComputation(5)); // Computes and caches the result console.log(memoizedComputation(5)); // Returns the cached result

In this example, the expensiveComputation function is passed to the memoize function to create a new memoized function memoizedComputation. The memoized function is then called twice with the same argument 5, and the cached result is returned the second time.

Best Practices for Using Memoization

While memoization can be a powerful tool for optimizing the performance of your application, there are some best practices you should follow to use it effectively:

  1. Memoize only pure functions: Memoization works best with pure functions that have no side effects and always return the same output for the same input. If a function has side effects or produces different outputs for the same input, memoization may not work as expected.

  2. Be aware of memory usage: Memoization can increase memory usage, especially if you are caching a large number of function results. Be sure to monitor memory usage and clear the cache when necessary to avoid memory leaks.

  3. Avoid using memoization for small functions: Memoization is most effective for functions that perform expensive computations or I/O operations. For small, simple functions, the overhead of memoization may outweigh the performance benefits.

  4. Use memoization selectively: Memoization can be a powerful tool, but it is not always necessary. Use

Read More

Temporal Dead Zone in Javascript

No Comments
admin
February 11, 2023

Temporal Dead Zone in Javascript

Temporal Dead Zone (TDZ) is a phenomenon in JavaScript that occurs when trying to access a variable that has been declared but not yet initialized. It is a common issue for developers who are new to the language, and can cause unexpected behavior in your code.

In JavaScript, variables are hoisted to the top of their scope, meaning that they are accessible from anywhere within that scope, even before they have been declared. However, this does not mean that they have been initialized, or given a value. Attempting to access the value of a variable before it has been initialized will result in a ReferenceError. This is known as the Temporal Dead Zone.

The Temporal Dead Zone can be encountered when using the let and const keywords to declare variables in JavaScript. These keywords were introduced in ECMAScript 6 as a way to improve variable scoping and reduce bugs caused by variable hoisting. Unlike the var keyword, variables declared with let and const are not accessible until they have been initialized.

Here is an example of the Temporal Dead Zone in action:

javascript
console.log(x); // ReferenceError: x is not defined
let x = 10;

In this example, attempting to access the value of x before it has been initialized results in a ReferenceError. The variable x is in the Temporal Dead Zone until it has been initialized.

It is important to be aware of the Temporal Dead Zone and to initialize variables as soon as they are declared, to avoid any unexpected behavior in your code. If you need to declare a variable but not initialize it immediately, you can use the following syntax:

javascript
let x;

console.log(x); // undefined


x =
10;

Here’s an example to illustrate the Temporal Dead Zone in JavaScript:

javascript
console.log(myVariable); // Throws a ReferenceError: myVariable is not defined 
let myVariable = 'Hello, world!';

In this example, we try to log the value of myVariable before it has been initialized. This results in a ReferenceError because the variable is in the TDZ and cannot be accessed until it has been initialized.

javascript
let myVariable = 'Hello, world!'; 
console.log(myVariable); // Logs 'Hello, world!'

In this example, we correctly declare and initialize the myVariable variable before trying to log its value. This code logs the string 'Hello, world!' to the console.

The TDZ is a feature of block-scoped variables (let and const), and it helps to prevent errors that can occur when variables are accessed before they have been initialized. It’s important to keep in mind when working with block-scoped variables in JavaScript to ensure that they are properly initialized before they are used.

In conclusion, the Temporal Dead Zone is an important concept to understand when working with variables in JavaScript. It occurs when attempting to access a variable that has been declared but not yet initialized, and can cause unexpected behavior in your code. By being aware of the Temporal Dead Zone and initializing variables as soon as they are declared, you can avoid these issues and write more efficient and reliable code.

Read More

Debouncing and Throttling in Javascript

No Comments
admin
February 11, 2023

Debouncing and Throttling in Javascript

Debouncing and throttling are two performance optimization techniques used in JavaScript to ensure that an event or function is not executed too frequently. These techniques are often used in web applications to reduce the number of times an event is triggered and to improve the overall performance and responsiveness of the application.

Debouncing

Debouncing is a technique used to limit the rate at which a function gets executed. When a user performs an action that triggers a function (e.g. resizing the window, scrolling, or typing in an input field), multiple events are generated in quick succession. If the function takes a long time to run, it can slow down the browser and lead to a poor user experience.

Debouncing ensures that the function is only executed once after a certain amount of time has passed since the last event was fired. This allows the browser to “breathe” between events and prevent the function from being executed too frequently.

Here’s an example of debouncing in JavaScript:

javascript
function debounce(func, wait) {

let timeout;

return function() {

const context = this;

const args = arguments;

clearTimeout(timeout);

timeout = setTimeout(() => {

func.apply(context, args);


}, wait);
};
}

const myFunction = debounce(function() {
// Do something here
}, 250);

window.addEventListener("resize", myFunction);

In this example, the debounce function takes two arguments: a function (func) and a wait time (wait). The returned function can be used as a replacement for the original function and will only be executed once after the wait time has passed since the last event was fired.

Throttling

Throttling is a technique used to limit the rate at which a function gets executed. Unlike debouncing, throttling ensures that the function is executed at a maximum rate. This means that if multiple events are fired in quick succession, the function will be executed at most once per interval.

Throttling is useful in situations where you want to ensure that a function is executed at a certain rate, but you don’t want to prevent it from being executed entirely. For example, when a user scrolls a page, you may want to update the position of an element on the page, but you don’t want to do this for every pixel the user scrolls.

Here’s an example of throttling in JavaScript:

javascript
function throttle(func, limit) {

let inThrottle;

return function() {

const args = arguments;

const context = this;

if (!inThrottle) {

func.apply(context, args);

inThrottle = true;

setTimeout(() => inThrottle = false, limit);


}
};
}

const myFunction = throttle(function() {


// Do something here
}, 250);

window.addEventListener("scroll", myFunction);

In this example, the throttle function takes two arguments: a function (func) and a limit (limit). The returned function can be used as a replacement for the original function and will be executed at most once per limit interval.

Here’s an example of throttling in JavaScript:

javascript
function throttle(func, delay) {
let timeoutId; 
return function() { 
const context = this; 
const args = arguments;
if (!timeoutId) { 
 timeoutId = setTimeout(() => {
 func.apply(context, args); 
 timeoutId = null; }, delay);
 } } } 
// Example usage function handleScroll() {
console.log('Scroll event triggered'); 
} 
const throttledHandleScroll = throttle(handleScroll, 500);
window.addEventListener('scroll', throttledHandleScroll);

In this example, the throttle function takes a func parameter (the function to be throttled) and a delay parameter (the minimum time interval in milliseconds between function calls). It returns a new function that uses setTimeout to delay the execution of func until delay milliseconds have passed since the last time the throttled function was called. If the function is called again before the delay has elapsed, the function call is ignored.

The throttled function is then used as an event listener for a scroll event on the window object. This ensures that the handleScroll function is called at most once every 500 milliseconds, even if the scroll event fires more frequently than that.

Conclusion

Debouncing and throttling are two useful performance optimization techniques used in JavaScript to improve the performance and responsiveness of a web application. Debouncing ensures that a function is only executed once after a certain amount of time

Read More

Closures in JavaScript

No Comments
admin
February 11, 2023

Closures in Javascript

Closures in JavaScript are a fundamental concept that allows developers to maintain privacy, state, and functionality in their code. They are one of the most powerful features of JavaScript and can be used in many different ways to create dynamic and maintainable applications.

A closure is a function that returns another function. The returned function has access to the variables and functions declared in the outer function, even after the outer function has finished executing. This allows the closure to maintain its state and reference values from the outer function, making it an ideal solution for maintaining privacy in JavaScript.

For example, let’s consider a simple closure that maintains a count of the number of times a function has been executed. Here’s an example code:

javascript
function counter() {

let count = 0;


return function() {

count++;

return count;

}
}


let count = counter();
console.log(count()); // 1
console.log(count()); // 2
console.log(count()); // 3

In this example, the counter function returns a closure that increments the count variable each time it is executed. The closure retains the value of the count variable even after the counter function has finished executing, allowing it to maintain its state between invocations.

Closures are also useful for creating private variables and methods in JavaScript. For example, you can use closures to create an object with private variables and methods, as follows:

typescript
function Person(firstName, lastName) {


let private = {};

private.firstName = firstName;

private.lastName = lastName;

return {

fullName: function() {

return private.firstName + ‘ ‘ + private.lastName;

}
}
}


let person = Person('John', 'Doe');


console.log(person.fullName()); // John Doe



console.log(person.firstName); // undefined

In this example, the Person function creates a private object with firstName and lastName variables. The closure then returns an object with a fullName method that has access to the private variables. This allows you to create objects with private state and methods that cannot be accessed directly, helping to maintain the integrity of your data.

In conclusion, closures are an essential part of JavaScript and provide a powerful way to maintain privacy, state, and functionality in your code. Whether you’re creating a counter or creating an object with private variables, closures are an essential tool for developing dynamic and maintainable applications.


javascript
function outerFunction() { 
let outerVariable = "I am from the outer function"; 
function innerFunction() { 
console.log(outerVariable); 
 } 
return innerFunction; 
} 
const innerFunc = outerFunction(); 
innerFunc(); // Output: "I am from the outer function"

In this example, outerFunction() returns innerFunction(), which is then assigned to the variable innerFunc. When innerFunc() is called, it logs the value of outerVariable, which is defined in the outer function.

This works because of closures. When outerFunction() is called, a new execution context is created and outerVariable is initialized. Then, innerFunction() is defined within this context, which means that it has access to the variables within that context, including outerVariable.

Even though outerFunction() has completed its execution, innerFunction() still has access to outerVariable through the closure. This allows innerFunction() to log the value of outerVariable even though it was defined in a different execution context.

Read More

Hoisting in Javascript

No Comments
admin
February 11, 2023

Hoisting in Javascript

Hoisting is a behavior in JavaScript that allows variables and functions declared in a code block to be accessible before they are defined or declared. This concept can be confusing for beginners and experienced developers alike, as it can lead to unexpected behavior and bugs in your code.

In JavaScript, variables declared with the “var” keyword are hoisted to the top of their scope, while variables declared with “let” and “const” are hoisted to the top of their scope, but they are not initialized until the line where they are declared. This means that variables declared with “var” will have a value of undefined until they are assigned a value, while “let” and “const” will remain uninitialized until they are declared.

For example, consider the following code:

javascript
console.log(a); // undefined
var a = 10;

In this code, the variable “a” is declared with the “var” keyword and is hoisted to the top of the scope. When we log the value of “a” to the console, it will output “undefined”, as the variable has been hoisted but has not yet been assigned a value.

Function declarations are also hoisted in JavaScript, meaning that they can be called before they are defined in the code. For example:

scss
sayHello(); // "Hello World"
function sayHello() {
console.log("Hello World");
}

In this code, the function “sayHello” is declared with the function keyword and is hoisted to the top of the scope, allowing it to be called before it is defined.

It’s important to note that while hoisting can make your code more readable and easier to write, it can also lead to unexpected behavior and bugs if not used properly. For example, consider the following code:

javascript
console.log(a); // 10
var a = 10;

In this code, the variable “a” is declared with the “var” keyword and is hoisted to the top of the scope. However, if you were to write the same code with “let” or “const”, you would get an error, as these keywords are not hoisted to the top of the scope:

javascript
console.log(a); // Uncaught ReferenceError: a is not defined
let a = 10;

In conclusion, hoisting is a behavior in JavaScript that allows variables and functions declared in a code block to be accessible before they are defined or declared. While it can make your code more readable and easier to write, it’s important to understand how it works and how to use it properly to avoid unexpected behavior and bugs.

 

Exapmle:

javascript
function greet() { 
console.log(message); // Output: undefined 
var message = "Hello, world!"; 
console.log(message); // Output: "Hello, world!" 
} 
greet();

In this example, greet() contains a variable declaration (var message = "Hello, world!";) and two console.log() statements. However, the first console.log() statement appears before the variable declaration.

Despite this, the code still runs without error and logs undefined to the console before logging "Hello, world!". This is because of hoisting, which is a JavaScript mechanism where variable and function declarations are moved to the top of their respective scopes before code execution.

So, in this case, even though the message variable is declared after the first console.log() statement, it is still hoisted to the top of the greet() function before the code is executed. However, its value is not set until later, which is why the first console.log() statement logs undefined.

It’s worth noting that only the declaration of message is hoisted, not its assignment. So, if we were to move the first console.log() statement after the message assignment, it would log "Hello, world!" instead of undefined.

 

 

Read More

Recent Posts

  • Interview Questions In ReactJs
  • Redux Toolkit in ReactJs
  • Redux in React js
  • How Javascript Works in Browser And How DOM Works In Web Browser
  • Feature of ES6 In Javacript

Recent Comments

No comments to show.

Archives

  • March 2023
  • February 2023

Categories

  • Advance Javascript
  • Interview Related Questions
  • Javascript
  • Nodejs
  • Reactjs

Search

Categories

  • Advance Javascript
  • Interview Related Questions
  • Javascript
  • Nodejs
  • Reactjs

Quick Link

Recent Posts

  • Interview Questions In ReactJs
  • Redux Toolkit in ReactJs
  • Redux in React js
  • How Javascript Works in Browser And How DOM Works In Web Browser
  • Feature of ES6 In Javacript
  • How Increase Performance of Reactjs​
  • Event Loop In Nodejs
  • how nodejs is works
  • Webpack in Reactjs
  • What is Bable

Categories

  • Advance Javascript
  • Interview Related Questions
  • Javascript
  • Nodejs
  • Reactjs

Copyright © 2017, All rights reserved