Can you explain the functionality of this Angular JS code snippet?

How is it possible that the following code snippet works in Angular JS?

var app = angular.module('store',[]); 



(function(){
    app.controller('StoreController',function(){
        this.blabla = student;
    });
})();

var student = 
{
    name:"Abc Def",
    rollNumber:12,
    isBrilliant: true,
    isMale:false,
    isFemale: false,
    istest:true
};

Despite the fact that student is defined after the function where it's being used and student isn't hoisted, why does the above function still work?

On the other hand, consider this example:

(function(){
        console.log("Name is :"+student);
    })();

    var student = {
        name:"xyz"
    };

This code snippet displays student as undefined, indicating that it wasn't hoisted.

Answer №1

.handler registers a handler function but does not run it immediately - it schedules it for a later stage. Afterwards, the user variable is provided with an object.

However, this handler function acts as a closure around the user variable - meaning it can access it during runtime. Learn more about closures by visiting this link. As a result, when it eventually runs, the user variable has been initialized.

In comparison, the alert.message in the second scenario, regardless of being encapsulated within an immediately-invoked function expression or not, runs prior to the assignment of the user variable, hence resulting in it being undefined.

Answer №2

The distinction between the initial example and the subsequent example is subtle but important. In the initial scenario, there are two function blocks present, while in the latter, only one exists.

Both examples are executed promptly, however, in the second instance, the function attempts to access an outer variable immediately, which has not yet been defined. Conversely, the first example simply performs a function to register the controller without executing its contents.

As the angular framework triggers the constructor function of the controller, the outer variable is already established and becomes part of the closure environment.

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 a problem while rendering the app: [TypeError: Unable to assign a value to the property 'content' since it is undefined]. Implementing Express with

My experience with res.render is flawless: res.render('main', function(err, html){ // Displays '<html></html>' from 'views/main.html' console.log(html); }); However, the situation changes when it comes to ...

Implementing a JavaScript Module Using JavaScript

I have encountered a simple problem. I am trying to use two JavaScript files: one following the module pattern and another one that calls the first one. I have tested all the code using Node.js and everything works fine when it is all in one file. However, ...

Using Ajax to implement a content slider with lightSlider

Seeking assistance in developing a dynamic content slider utilizing the LightSlider plugin. Currently, I have a script that fetches content from a database table (outputting JSON to HTML) and displays 6 div's of content per slide. However, I aim to di ...

Creating a canvas with multiple label introductions can be achieved by following these

I am looking to group labels and sublabels on the x-axis of a canvas component. Currently, I only have sublabels like: RTI_0, RTI_1... I would like to add labels to these sublabels like: RTI = {RTI_0,RTI_1,RTI_2] BB = {BB_0, BB_1,BB_2,BB_3] <div cla ...

How to delete a line from a file in Node.js without modifying the buffer variable

Hello everyone, I am just starting to explore the world of Nodejs Recently, I created a function that reads data from a file, saves it in an array variable, and then makes some changes to this variable before writing it back to the file. The code snippet ...

Identify the location of the mouse and activate a specific function based

Tracking the x-coordinate of the mouse is crucial in this scenario. When the mouse approaches a specific threshold (250px) towards the left edge of the window, it should trigger the function "openNav." The function should close when the mouse moves away fr ...

Is it necessary to include the jQuery-Do alert command before using console.log() in JavaScript or jQuery code?

const firstResponse = ""; $.get("firstCall.html", function (response) { processResponse(response); }); function processResponse(content) { firstResponse = content; } const secondResponse = ""; $.get("seco ...

Adding inline SVGs to a Nuxt 3 Vite project: A step-by-step guide

Hey there, I've been struggling with importing inline SVGs into my Nuxt3 Vite project. Any advice would be greatly appreciated. I discovered that using <img src="~/assets/images/icons/push-icon-chatops.svg" /> works, but I actually ne ...

How can we align the top edge of a div to the center of a circle within a separate div in a responsive manner?

I want to create 2 stacked divs: the first div contains a circular image, and the second div contains text. I want the second div to always cover half of the circle, with its upper edge positioned at the center point of the circle. This is my code: .cov ...

Can someone provide a sample using $httpBackend (ngMockE2E module service)?

Seeking the most straightforward method to integrate a mock backend service into my angular application. Any advice or pointers on creating a sample app that demonstrates how to implement this would be greatly appreciated. Thank you! ...

Looping through a Vue Bootstrap modal using a v-for directive

I am working on a Vue Bootstrap modal placed within a v-for loop. I need to replace the '1' in both 'v-b-modal.modal-1' and 'modal-1' with the index value, which I can access as {{ index }} while looping through the items. How ...

"Encountering a Javascript issue while trying to apply a CSS class to a

Encountering issues in Safari desktop / mobile and Internet Explorer. The error message states: In Safari: TypeError: Attempted to assign to readonly property. IE Edge: Assignment to read-only properties is not allowed in strict mode The problem arises ...

Learn how to create a dynamic React.useState function that allows for an unlimited number of input types sourced from a content management system

Currently, I am exploring the possibility of dynamically creating checkbox fields in a form using DatoCMS and the repeater module. My idea is to generate multiple checkbox fields based on the input from a text field in Dato as a repeater, which can then be ...

Vue.js causing issues with jQuery data table

Utilizing jQuery data-table within Vue.js in a laravel project has presented an issue for me. Although the data loads successfully into the data-table, there seems to be a problem with retrieving the data after it has been loaded. Specifically, the first r ...

Can a new EJS file be generated using the existing file as a template?

I am in the process of building a website navbar and I am curious about how to automatically inject code from one ejs file into another ejs file. In Python's Flask framework, this is accomplished using the principle of {% block title%} and in another ...

How can I track the number of correct answers in a ReactJS quiz with an auto-submit feature and a timer that stops?

The auto-submit feature is not functioning correctly. Although the code works fine when I manually submit the quiz at the end, if the time runs out, the score will always be 0/3 which is incorrect. // React and Material-UI imports omitted for brevity // ...

Error encountered: Required closing JSX tag for <CCol> was missing

Encountered a strange bug in vscode...while developing an app with react.js. Initially, the tags are displaying correctly in the code file. However, upon saving, the code format changes causing errors during runtime. For instance, here is an example of the ...

Is it possible to create a button function in HTML that can alter the CSS image tag?

Is there a way I could create a function that can retrieve a value, update an image source, and then incrementally select another value? It would be incredibly helpful if you could provide a reference where I could learn how to do this or explain it in det ...

Guidelines for utilizing React to select parameters in an Axios request

As a newcomer to ReactJs, I am working with a Product table on MySQL. I have successfully developed a dynamic table in the front-end using ReactJS along with MySQL and NodeJs on the backend. The dynamic table consists of four columns: Product, Quantity, Pr ...

What is the best way to eliminate the lower margin in the UI-Boostrap Angular Tab directive?

The ui.bootstrap.tabs directive, which can be found here, seems to have a default margin before displaying its content. https://i.stack.imgur.com/NECGA.png Here is the HTML snippet: <uib-tabset active="activeJustified" justified="false" id="tabSet" s ...