Will it function properly if it is (NULL)?

Here's the code snippet I'm currently using:

 <html>
    <head>
    <link type="text/css" rel="stylesheet" href="html.css" />
    <script type="text/javascript">
    function getName()
    {

    if(name)
    alert("Did you think I forgot about you, " + name + "?");
    else
    name=prompt("What's your name?","Please enter it here");


    }
    </script>
    </head>

    <body onload="var name;">
    <p onclick="getName()"; >Click here</p>
    </body>
    </html>

When I click the <p> text for the first time, it prompts me. However, if I click cancel without entering my name and then click the <p> text again, it doesn't prompt me anything.

Instead, it shows the name value as NULL. In C,

char a=NULL;
if(a)

evaluates to false. Does this same behavior occur in JavaScript?

Answer №1

It seems like you may come across an issue with setting the global variable name. When you set this, it actually affects the special property window.name, which persists even after refreshing the page.

To test this, try creating a page with the following script:

alert(window.name);
name = 'hello';

Initially, it will alert "undefined". However, upon refreshing the page, you should see "hello" instead.

To prevent this problem, consider renaming the variable name to something different.

Answer №2

give this a shot

if (name==undefined)
name=prompt("what is your name","enter here");
else
alert("did you think I would forget about you, " + name + "?");

Answer №3

This code snippet performs in the way you want, I believe: http://jsfiddle.net/YUCyL/5/

Upon observation, it appears that I have relocated the variable declaration to the beginning and updated its name to "username" instead of "name".

Answer №4

This situation is quite complex.

The term "name" holds significance in the global window object, hence it should not be used as a variable due to potential unreliability.

If you modify it to something like name$, your code will function correctly.

Furthermore, it seems that "onload" necessitates an expression rather than a statement, which is why using it in that way may cause issues. The usage with name appears to work because it is preassigned.

Answer №5

<html>
<head>
<link type="text/css" rel="stylesheet" href="html.css" />
<script type="text/javascript">
var username;

function retrieveName() {
    console.log(username, typeof name);
    if(username && username !== 'null') {
        alert("Did you think I forgot about you, " + username + "?");
    } else {
        username=prompt("What's your name?", "Enter here");
    }
}
</script>
</head>

<body>
<p onclick="retrieveName()"; >Click here</p>
</body>
</html>

Looking at the output in the console, it appears that the username is a string with a null value. This may seem odd, but it seems like window.username converts the value to a string, in this case, null.

NOTE:

It's advisable not to use the term "username" as it might conflict with existing reserved terms (used as a property in window).

window.username will return a string representation of its stored value. For instance:

window.username = null;

window.username === 'null' true

window.username === null 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

Unable to transfer files, encountering issues with PHP and AngularJS integration

I am currently working on uploading files using both AngularJS and PHP. For the AngularJS part, I am utilizing angular-file-upload from https://github.com/danialfarid/angular-file-upload. I suspect that the issue lies in my PHP code, as it fails to move ...

Obtain the final result once all promises have been successfully resolved in a loop

Here is an array of IDs: let idsArray = [1, 2, 3, 4, 5]; How can I ensure that a promise is returned only after all calls made within the loop are completed? let deferredPromise = $q.defer(), finalResult = []; fo ...

Can someone clarify the meaning of (e) in Javascript/jQuery code?

Recently, I've been delving into the world of JavaScript and jQuery to master the art of creating functions. I've noticed that many functions include an (e) in brackets. Allow me to demonstrate with an example: $(this).click(function(e) { // ...

Tips for shifting a stuck div 200px upward once the bottom of the page is reached while scrolling:

I've set up a page layout with two columns, one fixed and the other scrollable. The left column is fixed (containing Google ads) and stays in place as I scroll down the page. The right column displays posts and scrolls along with the rest of the con ...

Testing the updated version 18 of Create React APP index.js using Jest

Previously, I had this index.js file created for React version <= 17. import React from 'react'; import ReactDOM from 'react-dom'; import App from './views/App'; import reportWebVitals from './reportWebVitals'; im ...

Two approaches for one single object

I'm trying to figure out why this particular code works // ....................................................... var character = { name: 'Joni', type: 'blond', sayName: function() { return this.name; }, sayT ...

AngularJS controller experiencing scope() function returning undefined issue

I've been working with a function inside the controller: $scope.passValues = function (param1){ return "foo"; }; console.log($scope.passValues()); It logs foo, but then I tried this: $scope.passValues = function (param1){ return param1; ...

Is it possible to retrieve local variable JSON arrays using ajax/getJson()?

When starting a project without a database or data source, I often create json arrays in a *.js file to populate screens until the data modeling or database creation is complete. I am trying to figure out how to write an ajax/getJson() function to access ...

What is the best way to update the color of a label in a Mantine component?

When using the Mantine library, defining a checkbox is done like this: <Checkbox value="react" label="React"/> While it's possible to change the color of the checkbox itself, figuring out how to change the color of the label ...

When constructing a file directory URL, it is important to utilize the forward slash "/" in the filename

As I am creating a URL, the process involves taking the filename and using it to create a folder with that name. However, an issue arises if the name contains "/", as it causes the URL to break and creates an undesired location. For example: var fileDir ...

Using jQuery along with the jQuery Form Plugin to retrieve and parse the plain text responseText from an Ajax

I am currently working on creating a form using ajaxForm from the jQuery Form Plugin. var options = { target: '#output', // target element(s) to be updated with server response beforeSubmit: beforePost, // pre-submit cal ...

The lookahead will only find a match if there are brackets present within the string

Trying to use a negative lookahead to search for a particular pattern within a single line string: /\s+(?![^[]*]).+/g Applicable to the following cases: // Case 1 a.casd-234[test='asfd asdf'] abc defg // Case 2 asf.one.two.three four fiv ...

Having trouble storing radio buttons and checkboxes in MySQL database using AJAX

My app is facing an issue where radio buttons and checkboxes are not correctly entering information into the database. Currently, only text fields are successfully saving data, while checkboxes and radio buttons are only recording the value of the first ra ...

Inquiries about the jQuery Button Timer

Currently experimenting with jQuery to create a timer. Everything seems to be in place and the Stop Timer button is functioning properly. However, I'm facing issues with the Start Timer and Reset Timer buttons as they are not working as expected. Seek ...

What is the best way to incorporate a JavaScript file into my ejs file using node.js?

As I work on creating a website for my school project, I encountered a challenge involving including CSS files in node.js. Thankfully, after researching on stackoverflow, I was able to find a solution. Now, I am facing another issue - how to include a java ...

How can a Chrome extension transfer an ArrayBuffer or Blob from a content script to the background script without compromising its data type?

In my current script, I am downloading binary data using XHR in the content script and sending it to the background script: let me = this; let xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.responseType = 'arraybuffer'; xhr.onlo ...

Modify the values of all cells within a specific column in a table by utilizing a 2D array for both rows and cells

https://codesandbox.io/s/1p770371j The demonstration above showcases a table where data can be modified in each cell, and the 2D array keeps track of which row and column the data changes occur. A new button has been added to the column header titles. Th ...

Access the most recent state value with React's Context API

Trying out the React context API, Take a look at the someComponent function where I pass the click event (updateName function) to update the value of state.name from the GlobalProvider function. After updating state.name, it reflects in the browser but t ...

Error encountered: Unable to access the 'Lastname' property as it is undefined

Even though the console displays the value of $("#surname").val(), I am still encountering an error. Could it be that the script is executing before the form is dynamically built? $(function () { $("#addEmployeForm").submit(function (event) { ...

What steps can I take to improve my routing structure in nodejs and express?

My current WebAPI code is pretty modular, but I want to make it even more so. Right now, all the routes are in my server.js file and I would like to separate them into individual controllers. Any suggestions on how to achieve that? Here's an example: ...