Weird Javascript If Statement - javascript

I'm not sure whats wrong with my if statement. I'm trying to use my model inside my javascript.
if (#Model !== null)
{
if (#Model.Level !== null)
{
//use #Model.Level
}
}
else
{
//use default
}
The Model is null, but it still steps into the first if statement (and breaks on the second one obviously). I've tried #Model, !#Model and != but it still always steps in.
What am I doing wrong? (It's also got squiggly red lines under both !== saying there is a syntax error)

Triple equations work without type castings in JavaScript. In your case you are might get an undefined object which isn't a null value.
For example:
undefined === null //Do not cast when comparing, increased performance.
false
undefined == null //Do cast when comparing, decreased performance.
true
In addition, if #Model value is null then you won't see a null value on client side. It gives you an empty value like this:
if( == null)
{
}
This will cause an error on your javascript side. Null check should be done at server side. For that reason you have to put # value in front of your code to make it server side:
<script>
#if (Model != null) //Server side code.
{
if (Model.Level != null) //still server side code.
{
<text>
alert("your javascript here"); //write javascript on your screen.
</text>
}
}
</script>

In order to check if something is null or undefined in javascript, use if (#model) rather than if ( #model !== null)
http://appendto.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-2/

The reason why it steps into the if statement is because it evaluates to true, no weirdness to be found here. Your browser is not temperamental. For a list comparisons check out this http://dorey.github.io/JavaScript-Equality-Table/
Also note that there is a difference between double and triple =. Triple will type cast

This code looks a LOT like a Razor then Javascript, though you may be trying to mix the two of them together.
Your choices:
1) Convert Model to a JavaScript object using something like this:
Turn C# object into a JSON string in .NET 4
2) Use the Razor if statement and write out your final JavaScript with it.
<script>
// Code assume this is an numeric value
var useThisVariable;
</script>
if (#Model !== null)
{
if (#Model.Level !== null)
{
<script>
useThisVariable = #Model.Level;
</script>
}
}
else
{
<script>
useThisVariable = -1;
</script>
}

Related

js doesn't execute 'else' statement

I have an if-else statement in JavaScript which returns false, but doesn't execute the code inside 'else'.
part of the script inside the cshtml file:
if (#Session["mission"].ToString() != "1") {
setInterval(function () { myTimer(ctxPoints, ctxLines); }, 1000 / #ViewBag.rate);
} else {
alert("hi");
}
In the debug the '#Session["mission"].ToString() != "1"' statement returns false, but nothing jumps to the screen.
You should open your web browser Developer console and see the real script which reaches the browser.
The Razor parts, #Session["mission"].ToString() doesn't exists in the browser script, because they are evaluated in the server, before sending them to the browser. So it makes no sense to try #Session["mission"].ToString() != "1" this in the console. In the browser you will get something like:
if (1 != "1")
or even like
if ( != "1")
which would provoke an error.
JavaScript does coalescing, so 1 is equal to "1" when you use the comparers == or !=, so you don't need to include the qoutes around the value (unless you get the error mentioned above: in this case, if you included the quotes, you'd get if ("" != "1")).
Coalescing is avoided by using the !== or === which would consider 1 not equal to "1", so, including the quotes doesn't make any difference in this case.
I think you should clear Js code and c# code
if ("#Session["mission"].ToString()" != "1")
Session["mission"].ToString() this print string in c#, but you need to encapsulate it in quote to make this value get type string

Check for array in JS

I'm trying to check a value in JS that on page load is returned as a single-element array and after an ajax function returns as a string. I don't know why it's doing this but I'm trying to role with it.
So, using console.log(value) I get array ['Scranton'] on page load, and the ajax even returns string "Scranton"
When trying to check this variable, this does not work as I intended:
if ( value === 'Scranton' || value === ['Scranton']){
...
}
Any help is appreciated!
This would probably work but I would try and fix the underlying issue instead of working around it.
if ( value === 'Scranton' || value[0] === 'Scranton'){
...
}
You can use indexOf for both an array and a string, so value.indexOf("Scranton") !== -1 will work (just tested this on the console).
However you must first check for null/false/undefined or it will error.
if (value && value.indexOf("Scranton") !== -1) {}
EDIT: As Felix said, this will also be true for any string containing "Scranton". If this is a problem, then you can check for indexOf == 0 instead, which will be true for any string starting with "Scranton". It really depends on your concrete problem if this solution fits you. Use with care.
if (Object.prototype.toString.call(value) === '[object Array]') {
if (value.indexOf('Scranton') != -1) {
/* */
}
} else {
if (value === 'Scranton') {
/* */
}
}
Edit 1:
First, you need to check if "value" is an array. If it's an array and contains the string "Scranton", you can find it using value.indexOf().
And if "value" is not an array, you can directly compare it with the string 'Scranton'.
What does "after an ajax function" mean? The page loads with a default variable that has been assigned an array value, and then an Ajax request is made, which changes this default variable, and instead of an array being assigned, it assigns a string? Assuming this "ajax function" changes the default variable to the response text from the server, there is your problem: Ajax--like any other request--is text-based, so it is a string. If you are responding to the Ajax request with a JSON string, built on the server, it needs to be parsed in the browser, so it can be reinterpreted as an array. See the JSON.parse method.

Evaluate prompt value wont

I'm very new to JS - only a couple days in.
Trying to write a very basic prompt evaluated by an if statement.
When I run the code below, the user is prompted, but the statement is never evaluated by the if statement.
Any help? -- I realize the answer is probably simple and obvious, but as a SUPER beginner, what do I do?
var bool = prompt("What is an example of a boolean?");
if (typeof(bool) === "boolean") {
print("correct! that is a boolean");
print(bool) ;
};
In this case, assuming the user inputs something in the prompt, the type of the bool variable will always be a string. You'd rather check if the input compares to the string "true" or "false" etc., like this:
if (bool.toLowerCase() == "true" || bool.toLowerCase() == "false") {
...
}

javascript undefined not null, not empty issue

Is the statement:
if(attachmentId!=null && attachmentId.length>0&& attachmentId !='undefined'){
//do something
}
equivalent to:
if (attchmentId) {
//do something
}
thanks for the help
Writing :
if (attchmentId)
is the equivalent of:
if(
attchmentId != undefined &&//NO QUOTE
attchmentId != '' &&
attchmentId != null &&
attchmentId != false &&
attchmentId != 0
)
They're not equivalent but the third test attachmentId !='undefined' was probably an error (did you want attachmentId !=undefined ?).
Another example of difference is that 0 doesn't pass the first test but pass the second one.
You must decide what's important to you before you try to write the test. If you know you start with a string and you want to test if it's defined and not empty, then you may use the second test.
It can be reduced to this:
if (attachmentId && attachmentId.length > 0) {
//do something
}
This will do for arrays and more complex objects that happen to have a length property. If attachmentId is supposed to be a string the code above will work the same, but the second part will basically be a noop, so you can just go with:
if (attachmentId) {
//do something
}
I am assuming the comparison against 'undefined' was a mistake - do that and you're not checking if something is actually undefined. You're checking it it is different from a literal string that says "undefined".
Also you check the variable first due to the short circuit rule. It it's either null or not defined you don't care about the rest. Otherwise, if you tried evaluating the length before checking if it's undefined or null you could throw an error there.

JQuery - write conditional when object property is blank

I'm trying to write a conditional for when an object property's value is blank, but it is not triggering. This is my code. Any idea how I should write this?
console.log(vid);
if (vid.video == undefined){
//DO STUFF HERE - Doesn't work
}
The "object" in the screenshot is referenced in the code above as variable vid. I also tried undefined in the conditional.
I see some misunderstading here:
You say when an object property's value is blank but your coded if (vid.video != ""){.
I think you need if (!vid.video) {
use this:
vid.video == undefined
Also what Andrew said. If you want to DO STUFF when the attribute is empty, you should Use "==", and not "!="
if(vid.video != "")
Are you looking to only execute code when video doesn't equal "" but if you want to execute code when it is equal to "" you need
if(vid.video == "")
However if you want to check to see if its undefined you'll need to do
if(vid.video === undefined){
vid.video is not defined here
}
or
if(vid.video){
vid.video is defined here
}

Categories

Resources