Javascript alert never fires - javascript

Here is my code in its entirety:
if( javascript.isGarbage() != true) {
alert('I am not garbage!');
}
Why does this not alert anything???

If that is your code in its entirety, then javsacript is not defined. This will throw an error when you try .isGarbage() on it. Also, the string you pass to alert is missing its closing quote, as Firas pointed out (I missed this at first!).
It's possible to correct this code one of two ways. You can make javsacript an empty object, and then it will no longer error.
var javsacript = {};
if (javsacript.isGarbage() != true) {
alert('I am not garbage!');
}
Alternatively, you can add an additional check to make sure javsacript is truthy, i.e. defined as an object or some other value that will prevent an error when calling isGarbage() on it.
if (javsacript && javsacript.isGarbage() != true) {
alert('I am not garbage!');
}
Note: I'm not sure if "javsacript" is supposed to be "javascript." Ultimately it does not matter since neither one have been defined.

jav-"sa"-cript isn't a real word. Does your code rely on "javascript" being properly spelled? Is that really your whole code, or is "javsascript" part of some library?
You'll have to declare var javsacript = somevalue somewhere first before it can be used in any meaningful way.

Related

Javascript If element not exist return, cause object not working

I have a problem when I am checking whether element exist or not.
I'm using return; if element does not exist on document. This method cause the whole object not working anymore.
look at this fiddle : https://jsfiddle.net/LcwLm5bb/
see this line :
$("#notExist").focus(); // this element not exist on document, so I call this below condition
if (id == null) {
return; // this will shutdown the object for executing other object;
}
// ^ this code will cause next object not working anymore.
$(".child3").html("hahahahahaha"); // <--- not working anymore
how to get this things work?
what's the best way for handling this issue?
so, the next object will execute without any problem.
what's wrong with my code?
Because you're aborting if there is no tag by that ID.
And you're selecting by class name, not ID.
Either, you need to change
if (id == null) {
into something like
if (id == null && cl.length == 0 && tag.length == 0) {
or you should rewrite your code to use something like querySelectorAll().
Updated fiddle.
The return construct will halt execution inside the scope of your code. So if the entire code you have posted is your script then once the return condition is met then anything after that inside the same scope will not execute anymore. Remember that everything in JavaScript is scoped to the function level.
Example:
//call test
test();
function test(){
if(1 === 1){
return;//<-- exits the function
}
}

Javascript syntax - If statements and Function calls

I have a syntax question, lets say i have the following function. It received text for spell check and returns the correct text or false in case the text was already spelled correctly.
var spellCheck = function (txt) {
var spelledTxt = spell(txt);
if (spelledTxt =! txt) { //the text had a typo.
return spelledTxt;
}
return false;
}
Now in a different function i want to call this function from an ElseIf statement, and i want to get into that statement only if the text had a typo which was corrected. something like:
if(something){
do something....
}else if(spellCheck(word)){
do something with the spelledTxt that was returned from "spellcheck"
}
Can i just do:
else if(var spelledWord = spellCheck(word))
do something with spelledWord.
I forgot a very important thing: spellCheck(word) is very heavy function and i'd like to avoid calling it if not needed. This mean that only if we arrived to the else if() it will be called, and not sooner.
Any expression is valid inside an if statement, and that includes an assignment expression. The value of an assignment expression is the assigned value.
In your case the return value of the function call is the value of the expression, but the var makes it a statement and not a simple expression.
You need to remove the variable declaration part from the statement and then it's fine.
Alternatively, you could simply do it like this:
else {
var spelledWord = spellCheck(word);
if(spelledWord)
do something with spelledWord
}
You can do that. The assignment operation returns a value, which you could use as a boolean expression.
But you should remember that:
In Javascript var statement is function-scoped.
There is a 'hoist' behavior in Javascript.
As a result of 1,2 and some later code refactoring, you could easily introduce a bug to this code.
Type coercion in Javascript is a bit messy.
Reading code with side effects, where one operation could lead to 2 different logic outcomes simultaneously - is really hard work.
I'd consider using the strict comparison operators at least: if (spelledWord = spellCheck(word) !== '')
And if it's possible, try to memoize (cache) results from calling spellCheck function. In that case, you wouldn't need to combine two operations into one at all.

Empty functions in Javascript

If I have something like this:
var blah = function() { };
and then later in code blah is being used, what is the JSLint hint that says remove the empty block?
I don't know what jsLint thinks but if this is a problem and you need a solution then you can do something like the following:
var blah = function() { return undefined; }; // or just return;
Update : I think, Bergi's guess is right because, on the jslint site in the Required Blocks section :
JSLint expects that if, while, do and for statements will be made with
blocks {that is, with statements enclosed in braces}.JavaScript allows
an if to be written like this:if (condition) statement;That form is
known to contribute to mistakes in projects where many programmers are
working on the same code. That is why JSLint expects the use of a
block:
if (condition) { statements; }
Experience shows that this form is more resilient.
So, It probably just checks for empty blocks { } and invalidate the blank function.
Use the lambda expression:
const blah = () => void 0;
This will make it clear that blah is an empty function that returns undefined.
If you are asking what JsLint option turns this warning off it is: "debug:true"
Strangely, the docs make no reference to this behavior:
"Tolerate debugger statements" | debug | true if debugger statements should be allowed. Set this option to false before going into production.
But if you look at the code, you can see that it won't warn you with the debug option set to true:
function block(kind) {
// A block is a sequence of statements wrapped in braces.
...
if (kind !== 'catch' && array.length === 0 && !option.debug) {
curly.warn('empty_block');
}
...
}
A lot of code checkers check for this sort of thing. It doesn't mean you should never have empty code blocks. Sometimes there are valid reasons for having them. But it often means that the programmer just forgot to write the implementation. :)
What I like to do is put a comment in the function body, explaining why it's empty. This should suppress the warning, but it may not depending on whether the code checker considers a code block with a comment "empty".
var blah = function() { /* empty because ... */ };
If you intend to use the function as a constructor with the new operator:
// Returns the instance that was just created with the new operator.
var ClassLikeFunction = function(){
return this;
};
On the other hand, if is intentionally a blank function with no return value:
// Returns the same value as a function that returned nothing.
var blankFunction = function(){
return undefined;
};
This
{
...
}
is considered a code block and the hint is letting you know that it is empty (there are no commands in it). You don't have to remove it though, as #Katana314 said, it could be intentional.
what let me to this question is that I had an empty function in my namespace
and when I called that function, and
TypeError: MyNamespcae.myFunction is not a function
so don't create an empty function, at lease add one statement like void(0); or return null;

How can I test if a variable is set using typeof?

Im trying to use typeof to determine whether or not a variable is undefined:
function reset_textarea(reset) {
if (typeof(reset) != 'undefined') {
...do stuff
}
}
Im calling it like this:
reset_textarea('hello');
Its not working and I can't seem to figure out why. The function fires normally if I remove the if statement, thus - the issue seems to lie in the way I am testing whether or not the variable is set. Any idea what is going on?
Well, typeof("hello") (type of string) is defined. It's a String. typeof(hello) (note missing quotes) is what you need. Does this work for you?
if(typeof(window[reset]) !== 'undefined') {
//...
}
You must understand the difference between a variable (hello) and a string ("hello"). Remember that window["hello"] is equivalent to window.hello, but more flexible.
You can test for the existence of a property with the specified name on window:
function reset_textarea(reset) {
if (typeof(window[reset]) !== 'undefined') {
// ...do stuff
}
}

Javascript function to encapsulate check if a variable is undefined?

I've been working on a javascript library, and I have a lot of redundant checks like this:
if(typeof foo !== "undefined" && foo !== null)
So, I wanted to create a function that will be a shortcut to this unwieldy check. So I came up with this:
function isset(a)
{
return (typeof a !== "undefined" && a !== null) ? true : false;
}
But, since the value could be undefined, and it attempts to use a possibly undefined variable, it turns out to be useless.
Is there a way to accomplish this without have to extend a native prototype?
It really depends on what you mean by undefined.
1. You mean the variable does not exist.
In this case, what you want is not possible. typeof is an operator and therefore has magic behavior you just can't emulate using the language. If you try to pass a variable that doesn't exist to your function, it will throw a ReferenceError.
(See below for a workaround.)
2. You mean the variable has the value undefined, but does exist.
In this case, your function will do the trick -- though it could be simplified to the following:
function isset(variable) {
return variable != null;
}
This function will return false if the variable is either undefined or null. It takes advantage of the fact that undefined == null in JavaScript. Of course, with such a short function, one could argue that the function isn't needed at all.
Recall that a variable that is declared has a value -- undefined -- by default.
The name of your function suggests you mean case #1. I don't know what sort of library you are writing, but I can't imagine a case in a library where you would need to check if a variable exists, though I can definitely think of many possibilities for case #2.
If case #1 is necessary, remember that you can re-declare variables without changing their value:
a = 1; // pretend this was set somewhere higher up in the code
var a; // this does not change the value of `a`
If you re-declare variables before you use isset, you could avoid the ReferenceError problem. You won't be able to tell if the code has already declared the variable, though; you will only be able to tell if they have not assigned it to some other value.
You can check for null and undefined at the same time by using != instead.
// checks for both null and undefined
if( foo != null ) { ...
...so no need to use a function to shorten it.
null and undefined also evaluates to false in an if statement. So the following statement also works:
if(!foo)
...
This should cut it down significantly.
I do not understand why people keep promoting if (var) or if (!var). Both fail in my browsers. Meantime if (obj.prop) passes. This means that we should use if (this.someVar) or if (window.someVar) instead of if (varbl). Ok?

Categories

Resources