Explanation of JavaScript var declaration behavior

Check out this code snippet:

"use strict";

function isGiven(input)
{
    return (typeof (window[input]) === "undefined") ? false : true;
} 

try
{
    isGiven(existing);
}
catch (err)
{
    var existing = false;
}

existing = true;

Could someone clarify why removing the 'var' keyword causes an exception to be thrown, while including it treats the variable as undefined?

Answer №1

Strict mode in JavaScript restricts access to variables that have not been previously declared. This means that the variable isTrue must be declared before it can be accessed. If you remove the var declaration in front of it and it is not declared elsewhere, an error will occur.

The MDN page on strict mode explains:

In strict mode, creating accidental global variables is prevented. In regular JavaScript, mistyping a variable in an assignment would create a new global property and still "work," but may fail in the future. Assignments that would accidentally create global variables throw errors in strict mode:

Your question about undefined is more complex due to variable hoisting. In your code with the var statement, it is equivalent to this:

var isTrue;
try
{
    isDefined(isTrue);
}
catch (ex)
{
    isTrue = false;
}

isTrue = true;

So, when you call isDefined(isTrue), the value of isTrue is undefined because it has been declared but not initialized yet. Without the var statement, referencing isTrue in strict mode will result in an error since it has not been declared at that point.

If you only want to check if a variable has a value, you can do:

if (typeof isTrue != "undefined") {
    // code here for defined variable
}

Or, if you want to ensure it has a value even if it hasn't been initialized, you can use:

if (typeof isTrue == "undefined") {
    var isTrue = false;
}

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

Exploring ReactJs for conducting searches within a list of items

Utilizing the React material-ui search bar to search for specific items within a list has presented challenges. I have successfully created the search bar component, which receives an array of items from the list component as a property. The main issue li ...

Jest tutorial: mocking constructor in a sub third-party attribute

Our express application uses a third-party module called winston for logging purposes. const express = require('express'); const app = express(); const { createLogger, transports } = require('winston'); const port = process.env.PORT | ...

Show the comment section only if the initial radio button is selected

I am struggling to implement a comment section that is displayed when the first radio button is checked. Here's the code I have tried: I attempted the following to show the section and test the associated script: <div id="commentaryDiv" ...

The functionality of Ajax is currently disabled on the latest mobile Chrome browsers

I have successfully created a modal form with dependent dropdown lists, and I am populating these lists using an ajax call. The functionality works smoothly on desktop browsers and most mobile browsers, but there seems to be an issue on certain newer versi ...

Utilizing 'moment.js' for implementing a personalized date stamp in node.js

Is there a way to properly utilize moment.js for saving a created date into mongoDB through a form? Currently my code looks like this: var blogSchema = new mongoose.Schema({ title: String, image: String, body: String, created: {type: Date, ...

Polymer: Basic data binding is not functional in the second element

After dedicating 6 hours to this problem, I still can't seem to find a solution. Below is the code snippet from index.html: <flat-data-array availableModes="{{modes}}" id="dataArray"></flat-data-array> <flat-strip-view availableModes=" ...

What is preventing the listener from activating?

I came across some HTML code that looks like this: <form id="robokassa" action="//test.robokassa.ru/Index.aspx" method="post"> <input type="text" id="OutSum" name="OutSum" value="" placeholder="Сумма пополнения"> ...

I need help fetching the selected value instead of the option value in PHP

Can anyone offer some assistance with my issue? I have an HTML and PHP function where I am trying to echo a selected value, not the option value. Here is the desired output: "Patrick or any other name when I select and send the button" <?php ...

Is there a way for me to retrieve the value from an input, round it up to the nearest even number, and assign it to a new variable?

I am working on a project that involves two text boxes and a drop-down menu for providing rates. The values in the text boxes are given as inches. I want these inputs to be taken as values, rounded up to the next even number, and then set as variables. How ...

Ways to identify when a browser has disabled JavaScript and present a notification

Is there a way to detect if JavaScript is disabled in the browser and show an error div instead of the body? ...

The function stringByEvaluatingJavaScriptFromString is failing to execute

I have tackled similar problems that have been posted in this forum, however my issue remains unresolved. I am attempting to utilize stringByEvaluatingJavaScriptFromString in swift, but it is not functioning as expected. Any assistance would be greatly app ...

A guide to successfully interacting with multiple elements simultaneously at a single spot

Within my graphic chart, I have various dots that may be located in the same spot. I am looking for a way to handle clicks on two or more elements simultaneously in Vue 3. Do you know of any straightforward methods to achieve this? I attempted using refs ...

I'm curious about the outcomes of the JavaScript test. Could someone provide an explanation

Recently, I was in the process of writing a blog post discussing the importance of checking for the existence of jQuery elements before attaching event handlers. To illustrate this, I quickly created a jsfiddle example here. What puzzles me is that the re ...

Symfony2 requires clarification and direction when it comes to managing quantities in a shopping cart

My current challenge involves managing quantities in a shopping cart. I can easily add, delete, and view products in the cart, but am struggling with increasing or decreasing quantities if a user wants to purchase multiple units of the same product. BACKG ...

The absence of a base path in NestJs swagger configuration

Everything was running smoothly on my local machine. However, I encountered a problem after deploying the application. After deployment, /querybuilder gets added to the base URL. Therefore, http://localhost:80/helloworld turns into http://52.xxx.xxx.139/q ...

Locate items that possess identical property values and append them to a new array as a property

I am dealing with an array containing objects that have a specific property called "operationGroup" with the sub-property "groupId". Here is an example of the array structure: [{ operation: 11111, operationGroup: null }, { operation: 22222, ...

Displaying genuine HTML content in a React application using Algolia Instantsearch

After setting up a demo app using React with an Algolia search feature, I uploaded some indices into Algolia. The content consists of raw HTML. Is there a way to display this content as real HTML using Algolia? ...

What is the best way to ensure a bottom tooltip stays perfectly aligned with the right edge of its corresponding element?

Currently, I am trying to implement a tooltip above my progress bar. However, the small tooltip that I have is not functioning correctly... This is how it currently appears: https://i.sstatic.net/ZJUyT.png I need the tooltip to display above the white d ...

Leveraging lodash for a double groupBy operation

Hey everyone, I'm working on categorizing an array of objects by a specific attribute. Initially, using groupBy worked perfectly fine. However, now I need to go a step further and group these categories based on another attribute. I'm facing some ...

Add an array into another array using a for loop, with the first result being duplicated

In this loop, I am facing an issue while trying to insert an array into another array. Here is the code snippet: function convertFormToArray(form){ var temp={}; var question={}; var allQuestions=[]; for (i = 0; i < form.length; i++ ...