What is causing the error in this JavaScript code?

I understand that in JavaScript only function declarations are hoisted, meaning it should print 30 after executing the function sum.

However, I am confused because it is saying diff is not defined. Shouldn't it have been hoisted as well?

sum(10, 20);
diff(10, 20);
    
function sum(x, y) {
  return x + y;
}
    
let diff = function(x, y) {
  return x - y;
} 

Answer №1

It appears that only function declarations are hoisted, not function expressions where a nameless function is assigned to a variable. The code snippet below demonstrates this concept:

sum(10, 20);
diff(10, 20);
    
function sum(x, y) {
  return x + y;
}
    
function diff(x, y) {
  return x - y;
} 

If you want to declare diff the way it was done in the original code snippet, you need to move it to the top of your code structure like this:

let diff = function(x, y) {
  return x - y;
} 

sum(10, 20);
diff(10, 20);
    
function sum(x, y) {
  return x + y;
}
    

Answer №2

Absolutely, let and const are indeed hoisted in JavaScript, however, they cannot be accessed before their declarations are evaluated during runtime.

Answer №3

You're trying to call the function before you define it.

Here's how you can make it work:

let subtract = function(x, y) {
  return x - y;
} 

function add(x, y) {
  return x + y;
}

console.log(add(10, 20));
console.log(subtract(10, 20));

Answer №4

As the function 'diff' is declared, it will be hoisted. However, at the moment when diff(10, 20); is called, the variable 'diff' will not yet be defined with the function itself. For further understanding, I recommend researching the topic of function declaration versus function expression

Answer №5

One key distinction is that Function Expressions do not get hoisted like Function Declarations

In JavaScript, function expressions are not hoisted, unlike function declarations. This means you cannot use a function expression before it is created:

console.log(notHoisted) // undefined
// even though the variable name is hoisted, the definition isn't so it's undefined
notHoisted(); // TypeError: notHoisted is not a function

var notHoisted = function() {
   console.log('bar');
};

https://developer.mozilla.org/en-US/docs/web/JavaScript/Reference/Operators/function#function_expression_hoisting


If you want the function to be hoisted, you should use a Function Declaration.

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

Is there any more Angular code to be bound using ng-bind-html or ng-bind?

Hey there! Just a quick Angular inquiry: <div class="_minimal_size margin_10_middle"> <div class="_50 espaciado_0_20"> <p ng-bind-html="eirana_knows.feedback"></p> </div> <br class="clear"/> </div ...

Can Express and React be used to pre-render server-side code together?

I created a basic Pokedex website with static content. To expand my skills, I incorporated React, Express, Node, and Redis into the project. The server side rendering is handled by Express, which retrieves data from Redis based on the slug and passes it t ...

Create a toggle effect similar to jQuery using JavaScript

Looking for pure JavaScript code to implement show/hide functionality similar to jQuery. Currently, I am using the following code: y=document.getElementById('regform').style.display; if (y == 'block'){ document.getElementById(&apo ...

Unable to retrieve uploaded files within the controller

Update with the latest code that helps solve my problem $scope.uploadedFiles = []; $scope.upload = function(files) { $scope.uploadedFiles = files; angular.forEach(files, function(file) { if (file && !file.$error) { ...

Algorithm for converting a 2D voxel map into a line may encounter occasional difficulty in progressing

For my game, I am dealing with a 2D voxel map stored as a 2D array where 1 represents ground and 0 represents sky. In the map, areas marked as 1 (ground) are represented by green boxes https://i.sstatic.net/rG7N5.png The algorithm initiates at the leftmo ...

Is it possible to utilize mathematical operators such as multiplication, division, addition, subtraction, and exponentiation to transform a non-zero numerical value into

I am currently working with Oracle Siebel software which supports JavaScript expressions using only specific operators such as multiply, divide, subtract, add, and XOR (*, /, -, +, ^). Unfortunately, other operators like ! or ? : are not available for use. ...

Is there a way to display errors during jQuery validation?

Is there a specific function that can provide all error messages generated during form validation? I attempted to use the defaultshowerrors() function, but it only shows errors for the current element being validated. Is there a way to retrieve all error ...

Using @react-three / react-three-fiber: Implement useLoader() to dynamically load a new file when props are updated

Presently, I have a functional react component that loads a gltf model during initial load. The path is passed through the props and this setup seems to be working well. However, when the props change and trigger a rerender of the component, I noticed tha ...

Utilizing the power of React components with a provider and connect functionality

Presented below is a React component: const CreateUI = () => { // The prop to be passed to the `WidgetUI` component. const data = state.data; // The main component of the application. return ( <Provider store={store}> <div> ...

Endless loops: How React JS components can render indefinitely

Every time I try to render a screen with the Bar component, it seems to get stuck in an infinite loop without even passing any data. I tested importing react-chartjs-2 and that worked fine, loading just once. However, the other bar chart keeps rendering co ...

Auto scrolling in React Native Flatlist

I'm working on a FlatList component that I want to automatically scroll. Below is the current code: <FlatList contentContainerStyle={{}} data={banners} renderItem={(item) => ( <Image source={{ uri: item.item ...

Enhance your browsing experience with Fire-fox add-on that automatically triggers JavaScript after YouTube comments have

I am currently working on creating an add-on for the Firefox browser. I have implemented a page-mod that triggers a script when specific pages (such as Youtube) are loaded, allowing it to communicate data back to the main script. However, I am encountering ...

What can you tell me about Page Event functionality in Datatables?

Curious question -- I'm currently seeking a practical example of how to implement a 'page' event in a project utilizing DataTables. The provided documentation can be found here -- http://datatables.net/docs/DataTables/1.9.4/#page. Despite t ...

Choosing a populated control using JavaScript results in an empty value

Within my ASP.NET applications, I incorporate a server-side HTML select control. <select id="CompanyDropDown" runat="server" style="width:330px"> </select> To populate and pre-select items in this control, I use a JavaScript function triggere ...

Crockford's method of replacing values with nested objects

/** Custom Supplant Method **/ String.prototype.customSupplant = function(obj) { return this.replace (/{([^{}]*)}/g, function (match, propPath) { var props = propPath.split('.'); var result = obj; f ...

What is the best way to create a clickable background for a modal window?

I am looking to add a chatbox feature to my website and have been utilizing Bootstrap Modal for this purpose. My goal is to keep the modal open even when the user clicks outside of it, while still allowing them to interact with the background of the websi ...

Launching a Nuxt.js Cloud Function

Is there a possibility to deploy a cloud function that allows for server-side rendering with Nuxt on Firebase? The issue lies in the fact that the Node version used on Firebase is 6.11.1 while the minimum required Node version for Nuxt versions 1 and above ...

What is preventing me from utilizing a custom Pin it button instead of the default one?

This might not be related to code, but I am facing an issue that I can't seem to resolve. I'm attempting to use a square .png image as a "Pin It" button instead of the default one provided by Pinterest. Below is the code snippet where I am imple ...

Fade into the world of jQuery with text gracefully appearing and disappearing, only to be replaced by new captivating

I am diving into the world of jQuery for the first time. Even though I'm taking an online class on it, using it in a website is completely new to me. My aim for the homepage is to have "Hello there" appear for 2 seconds, then fade out and be replaced ...