What causes variables and functions to behave differently when it comes to hoisting?

I've recently been delving into some documentation and have noticed some inconsistencies in hoisting patterns within JavaScript.

Consider the following examples:

When it comes to functions,

function abc(){
 console.log("worked")
}

abc();

OUTPUT : worked

In contrast,

abc();
function abc(){
 console.log("worked")
}

OUTPUT : worked

This behavior is due to hoisting, where memory space is reserved for 'abc' at the start of execution context.

However, this doesn't hold true for variables, leaving me pondering why.

For instance,

var a = "Hello"
console.log(a)

OUTPUT : Hello

**Then why the difference in the example below?

console.log(a)
var a = "Hello"

The above code results in "undefined"

As the script runs:

  1. 'a' is initialized as undefined first
  2. Following that, it gets reassigned to the value "Hello"

Despite this, the output still reads undefined

Any insights on this discrepancy would be greatly appreciated. Thank you for your time.

Answer №1

When you see the code below

alert(b)
var b = "Hi"

It's like the interpreter actually reads it as:

var b;
alert(b);
b = "Hi"

This is because of how the language is designed to function. Hoisting the initialization expression could lead to complications in various scenarios.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountered an error while attempting to load resource: the server returned a 404 (Not Found) status code when trying to load an image in an

I am looking to dynamically load an image when it is selected from a file picker dialog. The code provided below attempts to achieve this, however, the image does not load into the img tag. <script src="https://cdnjs.cloudflare.com/ajax/libs/jq ...

Adding a PHP file into an HTML page using JavaScript include

Recently, I was assigned to collaborate with a third-party vendor who displays movie times on their platform. We were given the opportunity to co-brand our website on their platform by creating a wrapper for our site. This wrapper would allow the movie tim ...

Unlocking the res property in index.js from an HTML script tag: A step-by-step guide

Can anyone help me with the access variable issue I am facing? I have two files, index.js and page.ejs. These files require me to create a timer linked with datetimes stored on my local server. //index.js.. router.get('/mieiNoleggi', functio ...

The use of a <button> element in a React App within a Web Component with Shadow DOM in Chrome disables the ability to highlight text

An unusual problem has arisen, but I have a concise example that demonstrates the issue: https://codesandbox.io/s/falling-architecture-hvrsd?file=/src/index.js https://i.stack.imgur.com/CkL4g.png https://i.stack.imgur.com/nDjuD.png By utilizing the divs ...

Issue occurred in module.js:341 while attempting to include android platform to ionic using command line

For my hybrid app development using the Ionic framework, I made sure to install all required dependencies like node.js and cordova. Following their Getting started guide, I reached step 3 which instructs running this command within the app directory: > ...

Bring in SASS variables to enhance Material UI theme in NextJS

Within my project, I currently have the following two files: materialTheme.ts import { createMuiTheme, Theme } from "@material-ui/core/styles"; const theme: Theme = createMuiTheme({ palette: { primary: { main: "#209dd2", contras ...

Unable to import local npm package due to an error

We are in the process of migrating multiple websites, each with its own project, to Vue.js. As we transfer files over and bundle them using Webpack, we have encountered a need to consolidate similar components and core JavaScript files into a shared librar ...

Ways to conceal a div using jQuery when the video source is missing

If there is no source in the video, I want to hide the video_wrapper class <div class="video_wrapper" style="width: 100%; height: 100%; display: none;"> <video id="df-video" playsinline="" webkit-playsinline="" style="height: 100%; width: 100%; ...

Troubleshooting Issue: Unable to Retrieve Loaded Record in Ember.js

I am facing an issue with accessing properties to change the header of my RESTAdapter after loading the user. Do you have any ideas why that might be happening? The code snippet in question is as follows: var user = ''; App.MainRoute = Ember.R ...

What is the best way to dynamically retrieve a URL and utilize it as a hyperlink using jQuery?

Is there a way to retrieve the current URL and use it as a link in jQuery? For example, if my browser is currently on page mysite.com/index.php?page=post&see=11, I would like to use this URL in my link and append /new/ after the domain name, like so: ...

The second jQueryUI datepicker instance flickers and vanishes when the show() function is triggered

I currently have two jQueryUI datepickers integrated into my webpage. The initialization code for both is as follows: jQuery("#departureDate").datepicker({ beforeShow: function() { getDatesForCalendar("outbound"); }, numberOfMonths: 3 ...

Switch between the table data elements in an .hta document

The response provided by Dr.Molle in a previous post here was accurate, but it only functioned with <div>. I am required to utilize <table>. Though I found a script that works flawlessly outside of my VBScript, it does not work when embedded in ...

What could be causing the error I'm encountering while running the 'net' module in Node.js?

I am currently working with .net modular and have opened TCP port 6112. var net = require('net'); var server = net.createServer(function (socket) { //'connection' listener }); server.listen(6112, function () { //'listening ...

Tips for implementing code to function across several images in HTML and CSS

Hey there, I'm currently working on a website project for my friend and I sometimes refer to www.w3schools.com for help with coding. I'm having trouble implementing a gallery feature where users can click on images to view them fullscreen. I foun ...

CORS problem in Chrome when using AngularJS and Symfony 3

I've been dealing with a bug on my backend and frontend for the past week. I created a REST API (php/symfony) to manage books and authors. Initially, I had trouble with cross-origin requests on DELETE, which has been resolved. However, now I am facin ...

What is the best way to make a container 100% tall and display a navigation bar?

Struggling to properly render my React page This is what I have: ReactDOM.render( <React.StrictMode> <Provider store={store}> <Router /> </Provider> </React.StrictMode>, document.getEl ...

Iterate through each element in the array and manipulate the corresponding data

I am trying to figure out a way to assign a unique id to each item in an array and send it to the "script.js" file for individual data processing. <script href="script.js"></sciprt> script.js: $(function(){ $('#box' ...

Please input the number backwards into the designated text field

In my react-native application, I have a TextInput where I need to enter numbers in a specific order such as 0.00 => 0.01 => 0.12 => 1.23 => 12.34 => 123.45 and so on with each text change. I tried using CSS Direction "rtl" but it didn't work as expec ...

The React loader fails to function properly when used with nested routes

I'm currently working on my App.js file where I have defined all the routes for my application. I wanted to implement React-Router data loader functionality. import React from 'react' import { Routes, Route, Navigate, RouterProvider, createB ...

Leaflet Alert: The number of child elements is not the same as the total number of markers

Encountering a problem with Leaflet clustering using v-marker-cluster. Within the icon createFunction of the cluster, the className of children is used to determine the cluster style. Here is a snippet of this function : const childCount = marker_cluster._ ...