TypeError, variable is undefined - javascript

I've got an issue with my code apparently..
function match2(string,pattern){
var patternUpper = pattern.toUpperCase(); // Change pattern to uppercase
var stringUpper = string.toUpperCase(); // Change string to uppercase
for(var i=0;i<stringUpper.length-1;i++){
if(stringUpper.indexOf(patternUpper.charAt(i))<0)
return false;
}
return true;
}
Not sure why Firefox debugger is saying "pattern is undefined", seeing as it was defined in the function, right?
Any help is much appreciated.
Liam
EDIT: It is also doing this for string. Saying "string is undefined" if I comment out the second line of that snippet.
match2 is being called here:
alert(match2("thisisatest","ahtsit"));
The result works as expected, but the issue is causing errors further down in my program I think.

When "pattern" parameter is undefined, no matter where in which browser, it means that something is wrong with calling the function and you need to check the call stack, one step before inside the function and see what is going on there when you pass the parameters. (By the way, do not name the variables by using keywords or class names, I mean the variable named "string")
Hope it helps.
Cheers

It can only happen if you don't pass the second argument or the second argument is undefined

Related

Why this ternary operator are not working ? is not ternary operator are functions?

I just learned about the ternary operator but it is not functioning like I expected. If find it really confusing. I get an error in the console over and over again, and I don't understand why.
A normal function gives me undefined, which is fine, but the ternary operator gives me a "not defined" error, but why?
Ternary Operator
var experiencePoints = winBattle() ? 10 : 1;
Error
VM363:1 Uncaught ReferenceError: winBattle is not defined
My function
function experiencePoints() {
if (winBattle()) {
return 10;
} else {
return 1;
}
}
And it gives:
undefined
I want to get undefined just like the normal function gives.
The error is not because you used the ternary operator.
The message is telling you that JavaScript cannot find a function named "winBattle()" anywhere in your code - or at least, not within the current scope.
As we will see in this demonstration, if you declare such a function, and make it return a simple boolean "true" value (just for example), then the error does not occur:
var experiencePoints = winBattle() ? 10 : 1;
console.log(experiencePoints);
function winBattle()
{
//I assume here you would have some logic to calculate the winner of the battle, and then return true or false depending on who won.
return true;
}
You will need to check the rest of your code, and either
a) create the function, if it doesn't exist
or
b) make it accessible from the scope where you are calling it. If you need help with this task, you will have to show us the rest of your code.
Here is some background information:
I think you may have mistaken the undefined you're seeing as the result of executing the "experiencePoints" function. It is not. It is simply the result of creating that function via the console. The console always shows the result of the line you just created, which in this case is nothing, because you're just declaring a function, not running anything which produces output. If you included that function in a web page you would not see such a message. You have never actually run that function. If you did (by writing experiencePoints();) you would almost certainly see the same error relating to winBattle(), since at the time you run the function, winBattle() does not exist.
The difference between that and your ternary operator code is that this line of code is not within a function, and is therefore executed immediately.
The two are not the same: the function experiencePoints only executes when it is called, but you are not calling it. Instead you enter the function definition itself which does not return anything, and so you see undefined in the console.
The variable assignment with the ternary operator is executed on-the-spot (it is not a function definition), and so winBattle must exist at that very moment. Apparently it doesn't, and so you get an error. If you would just do this:
var a = Math.random() > 0.5 ? 10 : 1
You will not get an error, because Math.random is defined. Also you will see undefined in the console, which is normal for a statement, like var.
Coming back to the function experiencePoints: you may wonder why you don't get the same error about winBattle there. It is because the function is not executed yet.
Until you actually call it, you still have time to define winBattle. If however you decide to call it without first defining winBattle, you will get that same error.
Now you can of course use a ternary operator in a function -- that would be a fair comparison. You can choose between several syntaxes. Here are two:
function experiencePoints {
return winBattle() ? 10 : 1;
}
or as arrow function with expression syntax:
var experiencePoints = () => winBattle() ? 10 : 1;
Again, here you would only get an error about winBattle when you call the function.

String Value from jQuery becomes undefined when passed as parameter

Good Day,
I am working on a pet project using NodeJS and Electron. It is basically a simple text editor at the moment. However I am running into an issue when trying to pass the value of a text-area to a function prior to saving to file.
Specifically when I call a function in another module, the value of the contents becomes 'undefined'. I suspect I am passing it incorrectly, or that it is being over-written between when I make the call and when the call executes, since strings are supposed to be passed by reference.
The code for the Renderer(index.html) is like this :
let otherModule = require('./js/otherModule.js');
let $ = require('jquery');
$('#btn_Save').on('click',() => {
// get the fileName, if empty propmt user with save dialog,
//log it to console for debugging
var contents = $('#txt_Content').val();
console.log('with:',contents.substring(0,9),'...');
var finalContents = contents; // (create a copy?)
if(//someConditionMet//)
{
var otherVar = $('#txt_Other').val();
console.log('Use:',otherVar.substring(0,9),'...');
finalContents = otherModule.someFunc(contents, otherVar);
}
//do something with final contents.
})// end of On-click
I have used console.log() to extensively evaluate the function and can confirm that up to the call to otherModule, the contents are correct, and match those in the textArea.It is once we are in the 'otherModule' that things go awry.
The code for the otherModule is like this:
const someFunc = function(contents, otherVar)
{
console.log('DoThings with:',contents.substring(0,9),'...');
// print shows the value to be undefined...
// do more things
console.log('Did stuff with otherVar:',otherVar.substring(0,9),'...');
// prints just fine as as expected.
// do more things
return someString;
}
module.exports = {
someFunc: someFunc
}
As mentioned in the comment, the very first line of the function logs the contents of the console, which displays the substring as 'undefined'.
Thank you for your time and your consideration!
// Extra context//
I have done some searching but beyond learning that strings are passed by reference and are immutable, I have not seen an answer to a question like this. There has been some discussion of closure issues, but usually in the context of events and callbacks, which I do not believe is the context here.
// Extra Information//
I have since found a solution to get my parameters to pass correctly. I have posted the answer below. I did two things:
1. Changed the function definition from 'const' to 'let'
2. Changed the order of the params, and removed the space following the comma.
If you get the value inside the if you should be fine.
if(//someConditionMet//)
{
var contents = $('#txt_Content').val(); //New line
var otherVar = $('#txt_Other').val();
console.log('Use:',otherVar.substring(0,9),'...');
finalContents = otherModule.someFunc(contents, otherVar);
}
I have found a solution to this problem. I am not certain why it makes a difference but I changed two things in 'otherModule'.
1. I changes the function from 'const' to 'let'
2. I changed the order of the parameters, removing the space after the comma
The new function header looks like:
let someFunc = function(otherVar,contents) {...}
I also updated the call to match the new order ( given):
finalContents = otherModule.someFunc(otherVar,contents);
I hope this helps someone in the future!

var x; ... x.trim(); Why sometimes it allows but sometimes it makes the rest of the code stop working?

This minor issue causes me 5 hours to fix. Finally I figured out. See this code:
<script language="JavaScript" type="text/javascript">
var x;
.... // a lot of codes here
var k=x.trim();
</script>
The above code made the whole app stop working!
I remembered that I used to do like that before but got no problem.
So, about var x; ... x.trim();, Why sometimes it allows but sometimes it makes the rest of the code stop working?
And what is the best code practice for it?
You can do like this:
if(typeof x === 'undefined'){
// your get an error message
}
else
{
var k=x.toString().trim();
}
Using strict equality operator === above is good idea there because in JS, you can name a variable as undefined too:
var undefined = "something";
So using === makes sure that you are really checking against undefined value for a variable.
trim is a function of String. Refer MDN - String.trim().
So when you apply it to an integer, it fails and throws error, causing you code to stop work
Example
try{
var a = 1;
console.log(a.trim());
}
catch(ex){
console.log(ex);
}
You can try to convert number to string using .toString() and then apply .trim()
try{
var a = 1;
console.log(a.toString().trim());
}
catch(ex){
console.log(ex);
}
I would expand Rajesh's answer. He's right, when you try to call a method that does not exist, a TypeError is thrown. The easiest and fool-proof approach would be to use try/catch to ensure that the rest of the code would be executed as it should. But it's likely that even if it does, you don't get the result you want.
I believe the best way to do would be to wrap the value you're having into String object. It's as easy as
var k = String(x).trim();
It does several important things:
Converts the value of x, whatever it be, into a string, i.e. when you check its type, it's always 'string' and is always an instance of the String object.
Ensures that the resulting value has the method trim which does what it should.
Doesn't throw any error, so the rest of the code is executed.
There may be several pitfalls. If x is undefined, null, NaN or an object, the result of String(x) would be, correspondingly, 'undefined', 'null', 'NaN', or '[object Object]'. If x is an array, it's a specific case, and the value would be the same as if you call x.join(','), for example
x = [1, 2, 3];
var k = String(x).trim; // k is now '1,2,3'
So always keep in mind what types you're dealing with.
Just as with String, you can cast variables to other types, but naïvely converting anything into a Number, a String or an Array is considered a very bad practice. You should always be somewhat sure what type you're working with.

JavaScript convert variable name into string

I have a function like:
function testFunction( option )
{
alert(option);
}
(the actual function does more than just answer the option)
And of course, it works if you do testFunction("qwerty");, or testFunction(myvar);, where myvar is a variable.
It does not work if I do testFunction(qwerty);, where qwerty is not a variable, as expected.
I was wondering if there is a way to make the function check to see if option is a variable or string (such as "qwerty" and myvar in the examples above) and if it is continue as normal and alert the string or the variable's value.
However, if it is not a variable or string, but is an undefined variable (such as qwerty in the example above) then I would like it to alert the name of the variable (qwerty in this case).
Is this possible?
Thanks!
Some more examples:
var myvar = "1234";
testFunction("test"); //alerts "test"
testFunction(myvar); //alerts "1234"
testFunction(qwerty); //alert "qwerty"
Your problem here is that testFunction(qwerty); will not even reach the function.
Javascript cannot interpret the variable 'qwerty' as it is not defined, so it will crash right there.
Just for fun, here's a way to do what you request, by catching the error thrown when you try to interpret an undefined variable :
function testFunction( option ){
console.log(option);
}
try {
var myvar = "1234";
testFunction("test"); //alerts "test"
testFunction(myvar);
testFunction(qwerty); //alert "qwerty"
}catch(e){
if(e.message.indexOf('is not defined')!==-1){
var nd = e.message.split(' ')[0];
testFunction(nd);
}
}
JSFiddle here
Bear in mind that you should absolutely never do that, instead, try using existing variables in your programs, it works better ;)

JavaScript crash after removing any trivial statement

I'm working on a short JavaScript program, which works perfectly fine ONLY if I inject any trivial statement--such as var asd;--at a specific location. The program is intended to demonstrate a simple encapsulation technique.
No other locations work. ANY trivial statement works.
This is not a DOM load issue since I'm not even dealing with the DOM.
version that works: (warning, 3 alerts)
http://jsfiddle.net/bZUm6/3/
version that does not work:
http://jsfiddle.net/bZUm6/2/
Please note the "var asd;" in the first version.
Can someone please tell me why?
I would really appreciate it.
Max
It's the semicolon removal that's breaking it.
It will work even if you change...
var asd;
simply to this...
;
The reason is that the next line of code starts with (, which happens to be wrapping a function with its closing ).
This is being interpreted as a function call operator, and is attempting to invoke the previous expression.
MyApp.util.toXML = function(options, obj) {
// your code
return result.join("");
}
// var asd; // removing the semicolon
// |------seen as invoking the result of the previous expression and passing
// v the function as an argument.
(function(toXML) {
// your code
})(MyApp.util.toXML);
// ^---------------^ This is then attempting to invoke the return value
// of "toXML", which if it successfully returned, returned a String, which
// can't be invoked.
When you do
MyApp.util.toXML = function(options, obj) {
}
(function(){
}());
you are actually invoking the function
MyApp.util.toXML = function(options, obj) {
}( function(){}()) );
You are forgetting the ; after the function definition
MyApp.util.toXML = function() {
// code
}; // this semicolon
You forgot a semicolon, that's all. See http://jsfiddle.net/bZUm6/6/ (working).
After a function assignment, never forget the ;!
http://jsfiddle.net/bZUm6/8/
You're missing a semicolon after the function. I suppose it evaluates to something else if you don't end the statement.

Categories