Creating variables inside an if statement in the JavaScript language

Is it possible to assign a value to a variable based on a condition like this?

if (k<12){

var Case=4;

} 

However, when I try to display this variable in the body of the page, it shows up as undefined.

document.write(Case);

Answer №1

Essentially, when you use the var keyword, it is hoisted and initially assigned the value of undefined.

Variable declarations in JavaScript are processed before any code execution takes place. A variable declared with var has a scope that is limited to its current execution context, which could be within a function or globally if declared outside any functions. If you re-declare a variable, its value will not be lost.

Here's the order of execution:

var Case;        // hoisted, value: undefined

if (k < 12) {
    Case = 4;
}

Answer №2

The reason you are receiving "undefined" is because the variable has not been properly defined. It is only assigned a value when the condition becomes true. To rectify this issue, ensure your code looks like the following:

var Case = null;
var k = 0;

if(k > 14) {
  Case = 3;
}

document.write(Case);

I trust that this explanation was beneficial to you.

Answer №3

let switchCase = 0;
if(m<12){
  switchCase = 8;
}
document.write(switchCase);

Make sure to initialize the variable first, so that it won't be undefined if the condition m<12 evaluates to 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

Guide to creating a new window without a menu bar for an onclick function in electronJS

After trying to remove the menu bar from the main window using win.setMenu(null) in the main.js file, I encountered a new issue. When opening a new window (referred to as the "add items window"), I struggled to find a way to hide the menu bar in it as well ...

An easy way to ensure IE opens PDF links in an iframe in a new tab

I've encountered an issue while trying to display pdf files on an html page using an iframe. Here's my code snippet: <iframe src="testfile.pdf" width="100%" height="100%"></iframe> My problem is that the links within the pdf always ...

Why isn't this working? I'm attempting to trigger a sound when I hover with my cursor, but it only plays when I click instead

When I click on it, it works fine. But I can't seem to get it to work on hover. Can someone help me out? This is the HTML code: <body> <audio autoplay id="HAT2" > <source src="OOOOO_1_HAT.mp3" > Your browser doesn't support t ...

Starting up various modules in Angular 6 using arrays

Can an array be declared and used to bootstrap multiple components in module.ts? I attempted the following: export var initialComponents = []; initialComponents.push(AppComponent); if(condition) { initialComponents.push(IchFooterComponen ...

Error in Angular-CLI: The return type of a public method from an exported class is referencing the name 'ErrorObservable' from an external module, but it cannot be named as such

Upon completing the development of an app that mirrors an existing Angular 2 (non-cli) application, I am encountering errors in several of my files now that the project has been transitioned to Angular-CLI. I am puzzled as to why these errors are arising i ...

Controlling MVC controls dynamically using jQuery

I'm currently working on a table that contains multiple editable fields corresponding to an MVC model object. Each row has a cell with two buttons that toggle between edit and save functions when clicked. I've successfully implemented a mechanism ...

Integration of Django, Angular, and databases in web development

My django project utilizes postgresql. I am exploring the use of angular as a front-end on my html pages. What is the recommended method to integrate angular js controllers into the django project for interacting with django models and the database, specif ...

Closing the modal by simply clicking outside of it's boundaries

Is there a way to close the modal by clicking outside of it using pure JS or AngularJS? I'm struggling to figure out how to implement this functionality. Any assistance would be greatly appreciated. View Fiddle .modalDialog { position: fixed; ...

Convert inline javascript into an external function and update the reference to `this`

I'm currently in the process of converting some inline JavaScript code triggered by a button's onclick event to a regular JavaScript function. In my previous implementation, I successfully used the "this" reference to remove a table column. Howe ...

What is the best method to handle errors when retrieving JSON data and updating it using fetch()?

I need to figure out a way for the setMessage not to appear when encountering a PUT ERROR 404 not found in the updateTemplate function. I attempted using catch(err) but was unsuccessful. Here is the complete code snippet: My unique version of the code... ...

Can a variable be declared within the path references of the Firebase database?

In an effort to update my app's database references, I am working on implementing specific Firebase rules that involve adding buildings and depts nodes inside the user node. This decision was prompted by a discussion on best practices for writing Fire ...

The issue of Elasticsearch results not being correctly parsed as JSON objects by JavaScript when retrieved from a Python client

I am facing an issue with extracting a Javascript object from the Elasticsearch(2.1.1) response received through my Python (2.7) client. Python code: es=Elasticsearch(); @app.route('/output') def findSpots(): lat = request.args.get('la ...

What is the best way to integrate passport with the existing bcrypt code in my project?

I've been struggling for hours trying to integrate passport with the existing bcrypt code in my project. I've read documentation, tried different things, and basically tortured myself for almost 15 hours. Can anyone take a look at my project and ...

Directives for Nested Elements in AngularJS

I am currently working on creating two custom elements: <accordion> and <accordion-group-active>. .directive('accordion', function () { return { restrict: 'E', replace: true, transclude: true, ...

Creating a functional component in React using TypeScript with an explicit function return type

const App: FC = () => { const addItem = () => { useState([...items, {id:1,name:'something']) } return <div>hello</div> } The linter is showing an error in my App.tsx file. warning There is a missing return type ...

Improving the code of a JavaScript compiler through refactoring

I recently delved into the intricacies of a JavaScript package compiler and decided to revamp its fundamental structure. Each time a string is compiled, it gets appended to the SrcTable array and then outputted. However, for the output to be obtained, the ...

What is the best way to integrate node.js with HTML?

I am currently utilizing node.js to interact with an API on the IBM Cloud platform. I have successfully accessed the response in my code, but now I need to pass this data to an HTML page using "res.send". How can I achieve this? Below is the Node.js code ...

Check the values in the folder and if the folder is not already in the array, add the object to the array. If the

In my directory tree, there are numerous sub-directories that contain even more sub-directories. Consider the structure: vvv example1 plugin1 plugin2 example2 plugin1 plugin2 plugin3 etc. I am trying to figure out how many times ...

What is the process of connecting two models in Mongoose?

In this scenario, we have two models - ProductModel and CategoryModel. The goal here is to establish a connection between creating a product (ProductModel) and assigning it to a category. The issue arises when the category field is not getting filled in t ...

Node: How can I retrieve the value of a JSON key that contains a filename with a dot in

I have a JSON file named myjson.json, with the following structure: { "main.css": "main-4zgjrhtr.css", "main.js": "main-76gfhdgsj.js" "normalkey" : "somevalue" } The purpose is to link revision builds to their original filenames. Now I need to acce ...