This gives correct answer:
<script type="text/javascript">
var numbers=[67,56,45,34,78,54,67,90,43,56,78,90,23,45,67,89,54,1];
var sita=0;
for(i=0;i<numbers.length;i++){
if(numbers[i]>sita){
var sita=numbers[i];
document.write(sita+" ");
}
}
</script>
This is not working:
<script type="text/javascript">
var numbers=[67,56,45,34,78,54,67,90,43,56,78,90,23,45,67,89,54,1];
for(i=0;i<numbers.length;i++){
if(numbers[i]>sita){
var sita=numbers[i];
document.write(sita+" ");
}
}
</script>
why?
as others have mentioned sita is undefined in the second example.
a larger or smaller comparison against undefined - in that specific situation of yours - always yields false, no matter against what you compare.
so, your expression translates to
if (false)
EDIT:
I completely missed line 5 of the second example because so many people wrote that the variable sita was undefined when in fact just it's value is undefined. So enabling strict mode won't do much good here. Anyways, just for reference, my original post:
To avoid mistakes like that you should always (or if not always then
at least while debugging) use the strict mode (available since
ECMAScript 5).
"use strict";
link:
What does "use strict" do in JavaScript, and what is the reasoning behind it?
Say you're the interpreter. And you've reached the line if(numbers[i]>sita){ what would you think, what value has the sita variable?
You have to define variabls before using them (like in the first example). Otherwise interpreter won't know what means that word.
In your first code example sita is defined just before the for and within your if statement. I would assume that your second definition var sita = numbers[i] should look like sita = numbers[i].
In your second code example sita is not defined before use - only within your if. So sita is undefined and your if condition won't check out and nothing will be printed.
Related
Similar in some sense to this question, but rather than waiting for any change in a particular variable, this would be by value: breaking on a particular primitive value (probably only particularly useful for numbers and strings) being assigned.
e.g. When watching for assignment of value 'asdf' (in some browser's dev tools or something like Firebug):
function example(){
var x = 'as';
x += 'df'; /*break here*/
return x;
}
y= example(); /*break here, as well*/
I suspect that the answer is that this doesn't exist (searching has turned up nothing), but just in case, I thought I'd ask.
What happens to JavaScript literals (strings, numbers) that are not bound (aka assigned) to a variable ?
// A comment
"Practically, also a comment"
var assigned = "something"
53
423.0022
NaN
"does it impact performance"
// or is it treated just like a comment?
The browser appears to ignore them, but I couldn't find a specific rule in the spec
These are "expression statements". Such expressions are evaluated, but since they are not assigned, their value is not stored. JavaScript engines are likely to detect those that have no side effects, and eliminate them as if they were never there.
But still at least one of those has an effect:
"use strict";
This has the meaning of a JavaScript directive
From the EcmaScript specification:
A Use Strict Directive is an ExpressionStatement in a Directive Prologue whose StringLiteral is either the exact code unit sequences "use strict" or 'use strict'.
Also note that other string literals may have a special meaning when used in the directive prologue:
Implementations may define implementation specific meanings for ExpressionStatement productions which are not a Use Strict Directive and which occur in a Directive Prologue.
It's just an expression statement that evaluates - without side effects - to a value that is discarded.
You can see it's the result of the statement if you try this in eval or a REPL.
The values are stored in memory, until they get cleaned up by the Garbage collector, since nothing is pointing to that place in memory.
Since the value is not being stored (i.e. no space is being allocated to hold your literal), it is more or less being ignored by the browser, and also no overhead for the garbage collector. At least the function of your code does not change. Your javascript file will of course be a tiny bit larger because it contains more (useless) text.
It appears to treat them as variables being inserted to nothing. It treats them as if they don't exist anyway. Try it:
function myFunction() {
"comment"
//Or comment
alert("hello");
}
<html>
<body>
<button onclick="myFunction()">Call Javascript</button>
</body>
</html>
As you can see, nothing happens when the empty string is there. This is an interesting question, so I would be very interested in hearing any other results.
I found a typo in one of my javascript files where there was an integer just sitting on a line on its own with nothing else. The file never errored out because of it so I was wondering, how does javascript handle or evaluate a line with just an integer on it and nothing else 'behind the scenes'?
The following is a valid statement:
4;
Of course, it would make more sense to do something like var num = 4;, but what you're doing above is the same thing, you're just not saving it's return value to a variable.
You can even have completely empty statements. The following is a valid, empty statement:
;
So you could have a program that looks like this:
var num = 4;
4;
;
Each of those lines would be valid.
Well, "5" is a code, that returns 5. You can try it out by opening Chrome Dev Tools (Press F12), then open console and enter a number. It will return a number, so it is valid piece of code.
You can write any expression in a line, in fact, it is referenced an ExpressionStatement in the grammar. So the line 4; is a statement, which evaluates, but never sotres it's variable; You can even leave the semicolon in most cases because of Automatic Semicolon Insertion.
These statements get evaluated, but then the resulting value is ignored, meaning that single number or string literals will not have any side effect (like 1+2+3;). However, calling functions or accessing variables or fields can have side effects (like: 1+a()+b), a gets accessed and called, b gets accessed).
But there are special cases, like "use strict";, which old engines just skip over as it is just a StringLiteral inside an ExpressionStatement, but modern browsers notice this line, and switch to strict mode.
this my very first question on stackoverflow, so please forgive me if I am not getting all the etiquette yet.
I am trying to work with a previous script written in JavaScript. There is an if conditional expression in the code that I do not understand. The reason it is confusing to me is because it has 3 arguments. I have never seen an if conditional expression like this in any language, or even in the JavaScript "if" tutorial on http://www.w3schools.com/js/js_if_else.asp. The code snippet I am working with looks like this
if (this.css(alldivs[i], "contentdiv", "check")){ //check for DIVs with class "contentdiv"
setting.contentdivs.push(alldivs[i])
alldivs[i].style.display="none"}
My question is: What does if(foo, bar, "check") mean? Is this an old deprecated string comparison function in JavaScript? Why are there 3 variables in the if conditional expression instead of 2?
What are the advantages of the previous code, compared to something like:
if (this.css(alldivs[i] === "contentdiv")
Thank you for your help.
What does if(foo, bar, "check")
When you have a conditional with comma separated expressions, only the last one matters (the previous ones are also executed, though).
Then, the code is equivalent to:
foo;
bar;
if("check") { /*...*/ }
But you have this:
if (this.css(alldivs[i], "contentdiv", "check"))
That means:
Run this.css(alldivs[i], "contentdiv", "check"), where this is an object which has a the method css (a method is a function which is a property of an object).
Check the returned value.
Maybe you will understand it better this way:
var temp = this.css(alldivs[i], "contentdiv", "check");
if(temp) { /* ... */ }
Let's break down what's happening here. In this line:
if (this.css(alldivs[i], "contentdiv", "check"))
You have two things going on.
You have a function call this.css(alldivs[i], "contentdiv", "check").
You have an if() that checks the return value from that previous function call
This would be equivalent to this expanded code:
var returnVal = this.css(alldivs[i], "contentdiv", "check");
if (returnVal) {
setting.contentdivs.push(alldivs[i]);
alldivs[i].style.display="none";
}
This:
if (this.css(alldivs[i], "contentdiv", "check")) {
Would be equivalent to this:
var temp = this.css(alldivs[i], "contentdiv", "check");
if (temp) {
So you see, it's not an if taking three parameters. It's an if with one parameter which happens to be a function call that takes three arguments.
It's hard to know what answer is going to help you, as your question is about code that doesn't appear in your sample. In this case:
if (this.css(alldivs[i], "contentdiv", "check"))
The condition is based on the return value of the call to this.css. In the sample you seem interested in:
if(foo, bar, "check")
The answer is that it's always going to evaluate as True because of the way the Comma Operator behaves in JavaScript.
So I have been working with javascript for a website I am designing, shocker I know, I was trying to find a way to test if a variable did not exist or wasn't defined. After getting through this I think being undefined and not existing are two different things. Also I think its highly unlikely I found a bug but maybe someone with a better understanding of Javascript can explain to me why the following code works the way it does.
<script type="text/javascript">
var t1="";
var t2;
if (t1==undefined) {document.write("t1 is undefined");}
if (t2==undefined) {document.write("t2 is undefined");}
</script>
The above code returns "t2 is undefined".
<script type="text/javascript">
var t1="";
if (t1==undefined) {document.write("t1 is undefined");}
if (t2==undefined) {document.write("t2 is undefined");}
</script>
This second code crashes I believe. So in the first code t2 exists but is not defined? and in the second code it needs to exist before it can be undefined? I just figured that if I did not write "var t2;" then tested for it, it would be undefined. Hopefully I have explained this question enough.
It's not a bug. In fact, the typeof operator is the only place where you can use an undeclared variable without getting an error.
See my answer Internet Explorer: "console is not defined" Error for a detailed explanation
edit:
This is how it's defined in the specs:
The production UnaryExpression : typeof UnaryExpression is evaluated as follows:
1. Let val be the result of evaluating UnaryExpression.
2. If Type(val) is Reference, then
a. If IsUnresolvableReference(val) is true, return "undefined".
...
Everywhere else, IsUnresolvableReference==true results in an error.
Well in your case if you have:
var t1 = "";
You will declare an empty string so it is normal to be "defined";
Whilst by doing:
var t2;
You are not defining it as any type of javascript object
It seems that there's a confusing naming convention here;
We can say in the first case, you define variable t2 itself but it does not have a value defined. You can think the "undefined" property as the "value-undefined" to be more precise.
In the second case, you have t2 variable itself is NOT defined, thus you will get an error when you try to use it in code: "variable undefined", this error is because of a different reason but it is named similarly, making the situation a little confusing. Think this error as "variable-undefined" to be more precise.
I think you can just use the property "null" instead of the "undefined" in the first case to be clear.
var t1="";
var t2;
if (t1==null) {document.write("t1 is null");}
if (t2==null) {document.write("t2 is null");}
and;
var t1="";
if (t1==null) {document.write("t1 is null");}
if (t2==null) {document.write("t2 is null");} // this line gives error because t2 variable is undefined