Understanding Javascript Scoping

<html>
  <head>
    <title></title>
  <script type="text/javascript">  
    var x = 1;
function y() {
    x = 10;
    return;
    function z() {}
}

</script>
  </head>
  <body>
<script type="text/javascript">
y();
alert(x);
</script>
  </body>
</html>

Having a background in C and Java, I've noticed that JavaScript has different scoping rules. I'm curious as to why this program is outputting 1 and how exactly it's functioning.

Answer №1

One interesting aspect of JavaScript is its function scope feature. Functions are actually "hoisted" to the top of their scope, which is typically the nearest function.

function x() {
    y = 20;
    return;
    function y() {}
}

The above code snippet can be understood as:

function x() {
    function y() {} // the function is hoisted
    y = 20;
    return;
}

When a function is defined using function y(){}, it behaves as if there was a var keyword present; that creates a local variable. Therefore, the statement y=20 refers to the local y, not to any global y.

For more information on this topic, visit:

Answer №2

This scenario involves a mix of variable scope and the way functions and variables are defined within a function.

By declaring a local function named a inside the b function, you essentially create a new variable within that function that takes precedence over any global variable with the same name.

No matter where a local variable or function is declared within a function, it will be created before the function's code executes. So, in the given example:

function b() {
  a = 10;
  return;
  function a() {}
}

is essentially equivalent to:

function b() {
  var a = function(){};
  a = 10;
  return;
}

When the value 10 is assigned to the variable a within the function, it replaces the local function with the number. In JavaScript, functions can be treated as first-class citizens, allowing them to be passed around like other values and replaced by different values.

Since the function only modifies the local variable a, the global variable a remains unaffected.

Answer №3

The scope in JavaScript is determined by the function it belongs to. Within your function b, the variable a is local and does not affect the global variable a.

Answer №4

If you're interested in learning more about scoping in the Javascript language, check out this helpful resource:

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

When combining Puppeteer with Electron, an error stating "Browser revision not found" may occur. However, this issue does not arise when running with Node

My attempts to make Puppeteer work in Electron have been with various versions of Puppeteer (v5.4.0, v5.4.1, and v5.5.0), on Windows 10/MacOS, and with different Node versions (v12, v14.0.1, v15.0.3). Trying a simple puppeteer.launch() in the main process ...

What is the proper way to define the scope for invoking the Google People API using JavaScript?

I am attempting to display a list of directory people from my Google account. export class People { private auth: Auth.OAuth2Client; private initialized: boolean = false; private accessToken: string; constructor(private readonly clientEmail: strin ...

Utilizing React Material UI for form validation with error handling and informative helper text

I recently created a form in which I needed to validate the inputs. During my research, I came across the material UI library that has an attribute called error boolean, and another attribute called helperText for the TextField input of the form. However ...

Create a customized bracelet with a specified number of colors in JavaScript

I encountered an interesting challenge recently. The task was to create a bracelet of length n using a set of specified colors, following certain conditions: No two adjacent beads should have the same color (e.g., R R). A pattern of three consecutive bea ...

Encountering an error: "Unhandled promise rejection SyntaxError: Unexpected character in JSON data at line 1 column 1."

When the submit button is clicked, my registration form data is sent using an event function called postData() in React. The user data is sent at the register route, and I have mentioned line numbers in the comments: const postData = async(event) =>{ ...

What is the best way to run a callback once several Ajax requests have finished?

I am facing a challenge with executing a callback function after multiple jQuery Ajax requests have been completed. The issue arises when these Ajax requests call another function, resulting in the functions being undefined. I suspect that the root of ...

What is the best way to vertically center an item at the end of a card in Bootstrap 4?

In the process of creating a long bootstrap card containing two rows of information including a title and description, I encountered an alignment issue with the button. The button is intended to be aligned to the right of the card while remaining centered. ...

What is the best way to integrate Halfmoon's JS from npm into my current code using Gulp?

I am eager to incorporate the Halfmoon framework into a personal project and have successfully downloaded it through npm. To utilize the example JavaScript provided on this page (found at ), I need to import the library using a require statement. var halfm ...

The link and source attributes are missing from the .ejs template

I am experiencing an issue where the href and src attributes in my .ejs file are not referencing my local files properly. My setup involves node.js and express. Here is a snippet from the .ejs template that is causing the problem. <head> & ...

Issues with JavaScript causing YouTube embed player to malfunction

For the past few days, I've encountered an issue where my JavaScript code to embed YouTube videos isn't working properly. The video loads but it's not playable as the play button is unresponsive. The console shows this error: Uncaught TypeE ...

Adding an item to an array in Angular 2 using JavaScript!

In my Angular2 form, I have a field that consists of an array of objects. I've successfully created a table with a Delete Row button for each row and an Add Row button using the push() and slice() methods in JavaScript. However, there's a major ...

The array's value fluctuates into a negative without any direct manipulation from my end

In order to work with the $scope.option value, I stored it in a temporary variable and then applied operations on the temporary variable after changing all the values of $scope.option to negative numbers. var app = angular.module('myApp', []); ...

The functionality of angular-ui's ui-utils and ui-scroll module is currently nonfunctional in version 0.1.0

I have been trying to implement the features from this Angular UI library: http://angular-ui.github.io/ui-utils/, particularly focusing on this aspect: https://github.com/angular-ui/ui-utils/blob/master/modules/scroll/README.md Unfortunately, despite my e ...

The jQuery div enclosure technique

I am trying to wrap HTML around an existing div, here is what I have attempted: HTML: <input type="text" data-placeholder="username" /> It should look like this when rendered: <div class="placeholding-input"> <input type="text" data-pl ...

What is the best way to modify the inline style width of a table td from pixels to percentage in order to make it

<table> <tr style="height:15pt;"> <td style="width:229pt;border-style:solid;border-width:0pt;padding:3pt 9pt 3pt 0pt;" valign="bottom" bgcolor="#c0c0c0"><p style="font-family:Times New Roman, serif;font-size:10pt;font-style:norm ...

Is there a way to modify the language for the 'months' displayed on the date axis in Chart JS?

I need to translate the month string on the date axis (x-axis) in my Chart JS data plot from '20 Dec 2018' to a different language. I thought it would automatically adjust based on the browser's language settings, but that doesn't seem ...

Issues with Bootstrap Navbar Dropdown functionality, including flickering or unresponsiveness

While working on a project, I incorporated the FlexStart Bootstrap Template. However, I encountered an issue with the Dropdown feature on the navbar. When hovering over the menu and submenu, they flicker incessantly. Despite investing a considerable amount ...

I'm having trouble getting this angular expression to cooperate in Plunker. Can anyone shed some light on why {{ 843 / 42

I'm currently diving into Angular with the help of Plural Sight. The initial lesson dives into utilizing the ng-app directive. For those interested, here's a direct link to the Plunker editor: http://plnkr.co/edit/HIDCS8A9CR1jnAIDR0Zb?p=preview ...

What could be causing NPM to generate an HTTP Error 400 when trying to publish a package?

My current goal is to release an NPM package named 2680. At the moment, there is no existing package, user, or organization with this specific name. Upon inspection of my package.json, it appears that everything else is in order. Here are all the relevant ...

Utilize Vue.js to transmit HTTP requests with specified headers and parameters

I'm trying to figure out how to create a LinkedIn login component, but I'm having trouble finding information about headers and parameters. Can someone help me understand how to send a GET or POST request with parameters and headers? Here's ...