Javascript variable is undefined outside if condition - javascript

I have defined a javascript variable but it returns undefined.
variable = "";
if(somecondition){
variable=myString.length;
}
alert(variable);
here variable returns undefined. If I keep the alert inside the if condition, I am able to get the value but its not working if I keep the alert outside the if condition.

Your myString does not have an property called length and hence you are getting undefined.
Usually, String, array has length property while objects don't have it.
Either you are invoking a wrong property or invoking it on a wrong data type or you have to define one yourself :P

Using var will do it:
var variable;

You need to declare and define your variable.
var variable = "";
if(somecondition) {
variable = myString.length;
}
alert(variable);

Are you missing the initialization of mystring?
Look at the following

var variable = '';
if (true) {
variable = 'Yes'
}
alert(variable);
This will show alert as Yes.
So in your case myString.length; is probably undefined

If variable isn't undefined in the function, it's because it is still equal to the initial value, "" (Empty String).
What I bet is happening, is myString is actually a number and not a string. Try the following and see if you are still having a problem:
variable = "";
if(somecondition){
variable=myString.toString().length;
}
alert(variable);

Related

Concatenating a declared but not defined variable

Out of curiosity I did this simple concatenation:
let a;
a+="hello"
console.log(a)
It returns "undefinedhello"
I get that a was basically the string "undefined", or is it converted to a string when concatenating? Is there something to learn here?
let a="";
a+="hello"
console.log(a)
since you are creating a variable here so the default value becomes undefined . You need to assign a value over there.
check here

My If Statement is not functioning in Jquery

I have assigned my selected option to a variable. However, when I use my if statement to compare the variable and a string, the if statement executes the code regardless of if the variable is equal to my string.
I have tried rewriting the code and doing some research on javascript if statements but, to my knowledge, I am unaware of any errors in my code.
$(document).ready(function(){
$("#main_dropdown").change(function(){
let selectedMajor = $(this).children("option:selected").val();
if (selectedMajor = 'arts') {
alert("Your selected major is: " + selectedMajor);
}
});
});
You are attempting to compare them using = which will actually assign 'arts' to the selectedMajor variable. Use == instead which will compare them.
If you need to make sure the types are the same as well, use ===.
In javascript = is used to assign a value to a variable, == is actually the eqaulity check operator.
Also use trim() function to check the compared value doesn't contain any leading/trailing space.
Try changing,
if (selectedMajor = 'arts') {
as,
if (selectedMajor.trim() == 'arts') {
Hope this helps!.
Your if statement is using the assignment =. You want to compare with the ==.
selectedMajor = 'arts' is an Assignment which will always return the value on left hand side.
Simple assignment operator is used to assign a value to a variable. The assignment operation evaluates to the assigned value
let x = 3;
console.log(x = 3)
If you want to compare the value you should Abstract Equality == or Strict Equality ===
let x = 3;
console.log(x === 3)

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 ;)

Set JavaScript variable = null, or leave undefined?

When declaring variables at the top of the JavaScript function, is it best practice to set them equal to null, or leave as 'undefined'? Another way to ask, what circumstances call for each option below?
Option A:
var a = null,
b = null;
Option B:
var a,
b;
It depends on the context.
"undefined" means this value does not exist. typeof returns "undefined"
"null" means this value exists with an empty value. When you use typeof to test for "null", you will see that it's an object. Other case when you serialize "null" value to backend server like asp.net mvc, the server will receive "null", but when you serialize "undefined", the server is unlikely to receive a value.
I declare them as undefined when I don't assign a value because they are undefined after all.
Generally, I use null for values that I know can have a "null" state; for example
if(jane.isManager == false){
jane.employees = null
}
Otherwise, if its a variable or function that's not defined yet (and thus, is not "usable" at the moment) but is supposed to be setup later, I usually leave it undefined.
Generally speak I defined null as it indicates a human set the value and undefined to indicate no setting has taken place.
I usually set it to whatever I expect to be returned from the function.
If a string, than i will set it to an empty string ='', same for object ={} and array=[], integers = 0.
using this method saves me the need to check for null / undefined. my function will know how to handle string/array/object regardless of the result.
The only time you need to set it (or not) is if you need to explicitly check that a variable a is set exactly to null or undefined.
if(a === null) {
}
...is not the same as:
if(a === undefined) {
}
That said, a == null && a == undefined will return true.
Fiddle
Be careful if you use this value to assign some object's property and call JSON.stringify later* - nulls will remain, but undefined properties will be omited, as in example below:
var a, b = null;
c = {a, b};
console.log(c);
console.log(JSON.stringify(c)) // a omited
*or some utility function/library that works in similar way or uses JSON.stringify underneath
There are two features of null we should understand:
null is an empty or non-existent value.
null must be assigned.
You can assign null to a variable to denote that currently that variable does not have any value but it will have later on. A null means absence of a value.
example:-
let a = null;
console.log(a); //null
You can use ''; to declaring NULL variable in Javascript

Put a variable between double quotes

I have a small question:
I have a function in javascript.
var func = function(variable)
{
result = variable;
}
If I call
func(rabbit);
I need the result to be "rabbit".
I cannot figure out how to put the variable between the two quotes.
Assuming rabbit is supposed to be a string:
func("rabbit");
If rabbit is actually a variable, then there's no way to do this because the variable (meaning the implementation's representation of a variable) isn't actually passed to the function, but rather its value is.
Actually there's an ancient way to retrieve the variable name.
var func = function(variable)
{
console.log(variable); // outputs "white"
console.log(arguments.callee.caller.toString().match(/func\((.*?)\)/)[1]); // outputs "rabbit"
}
rabbit = 'white';
func(rabbit);
See it running http://jsfiddle.net/Q55Rb/
You could do this
function whatever(input) {
return '\"' + input + '\"';
}
result should be in quotes
I could not tell from your question whether you wanted "rabbit" to be the property name, or the value. So here is both:
var func = function(variable) {
window[variable] = 'abc'; // Setting the variable as what is passed in
window.result = variable; // Normal
}
func('rabbit'); // Will set both window.rabbit to 'abc', and window.result to 'rabbit'
I wouldn't advise setting global variables, though. More info
Ok I thought that was my problem. Now I'm pretty sure that's not it but I have no clue what it is then.
I have this in my function:
defaults = {title :{'pan':-1,'left':0,'volume':0.30,'top':111}};
Where title is a variable from the function. But as a result I get title in defaults instead of the actual title stored in the variable named title. Do you understand me?

Categories