declaring a variable within conditional expressions (ternary operator) - javascript

Is it possible to declare the variable within a conditional expression?
for example:
The code below return a syntax error (because I've declared the variable x within the conditional expression?).
var a = document.getElementById("userData");
var d = a.value;
function() {
(d.length>15)?(
alert("your input was too long")):(
var x = parseInt(d).toString(2),
a.value=x
);
}
obviously this can be fixed by simply adding var x; outside the statement, but is it possible for variables to be declared here?

Is it possible to declare the variable within a conditional expression?
No. var is a statement, and the operands to a conditional expression are expressions. The language grammar doesn't allow it. Thankfully.

You can do this with an immediately-invoked function:
(d.length>15)?(
alert("your input was too long")):
(function(){
var x = parseInt(d).toString(2);
a.value=x;
}())
);
But note that the x variable will not exist outside of the inner function. (I can't tell whether you want it to exist after the expression is evaluated or not.)

No. But you can initialize it with undefined
and set it with condition.
function Test()
{
d = 25.6654;
var x = (d.toString().length > 15) ? parseInt(d).toString() : undefined;
alert(typeof x === "undefined");
}
Then you can work with if(typeof x == "undefined") //do something

Related

Output is giving "1undefined" for something that should be "1function" for sure. Where is the Mistake? [duplicate]

This question already has answers here:
typeof of a function not returning correct value but undefined
(2 answers)
Closed 4 years ago.
The example below must output for sure function, as the value of x is "1" (integer) and then we are passing a parameter named "f" (of a function). It doesn't matter whether this function does something or is blank, but I am sure -- that variable f --> points to function. so typeof(f) will surely return function.
Now, adding of an integer and "function" (as typeof always returns a string) is going to be a string --> 1function.
Now, amazingly the output is "1undefined". How?
<script>
var x = 1;
if (function f(){}) {
x += typeof f;
}
console.log(x);
</script>
As per answer by Ellepsis that declarations don't take inside if() braces and only boolean is returned. Explain this then, why is it returning 3?
<script>
var x = 1;
if (y = 2) {
x = x + y;
}
console.log(x);
</script>
if (function f(){}) {
A function declaration will create a variable with the same name in the current scope.
A function expression will only create a variable with the same name inside itself.
So the variable f only exists:
if (function f(){ })
^^^^
here
The function expression itself evaluates as a function, which the if statement picks up as a truthy value but there is no f variable in scope.
Explain this then, why is it returning 3?
You are explicitly assigning a value to a variable. That variable remains in scope.
You would get the same effect if you did this:
if (f = function f(){}) {
So:
(function f(){})
Creates a function
Names the function f
Creates a variable inside the function called f containing a reference to a function
Evaluates as a function, which is a true value, which is tested by the if
While:
(f = function f(){})
Creates a function
Names the function f
Creates a variable inside the function called f containing a reference to a function
Creates a variable f outside the function
function f(){} evaluates as a function and is assigned to f by the =
f = function f(){} also evaluates as a function, which is a true value, which is tested by the if
You are getting undefined because function f is not defined in the code anywhere. Writing the function inside an if statement does not define the function. The code just assumes it as a truthy value, a condition for the if statement but in real f does not exists. You can define f outside and it will work fine or you can just perform the assignment in the if and then also it will work
var x = 1;
if (f=function(){}) {
x += typeof f;
}
console.log(x);
var x = 1;
var f;
if ( f = function() {} ) {
x += typeof f;
}
console.log(x);

Unexpected token var when creating variable in if condition

I am creating variable and using it in for statement
for(var i = 0; i < 10; i++) {
console.log(i)
}
It is working properly and resulting from 1-10;
When I write same in the if condition
if(var value = 10) {
console.log("Evaluate");
}
It is resulting Unexpected token var.
When I declare a variable (var a = 10), resulting the same error. Is there any issue.
An if statement only accepts an expression inside (something that evaluates to a value). Something like var value = ... is a statement - rather than evaluating to a value, it does something (namely, creates a local variable bound to the name value). So, since var value = ... cannot be evaluated as an expression, an error is thrown.
Some things can be evaluated both as statements and expressions (such as functions), but variable creation is not one of them.
Note that variable assignment is possible inside an if, because assignment does evaluate to the value assigned:
var value;
if(value = 10) {
console.log('value now has the value 10');
}
But that's really confusing to read - a reader of the code will likely immediately worry whether that's a typo or not. Better to assign variables outside of an if condition, whenever possible.
Only use var when you want to create a new variable. If you simply want to check a variable (for example, check whether the variable named value is 10), then just print that variable name, and use a comparison operator (===, not =):
if (value === 10) {
// do stuff
}
When you write
var value = 10
actually evaluated as the following statements:
var value;
value = 10
You can not write statement in if as condition, as the condition must be only expression:
An expression that is considered to be either truthy or falsy.
Declare and initialize the variable outside. Use proper operators.
var value = 10;
if(value == 10) {
console.log("Evaluate");
}
else {
console.log("Hello");
}
You need to declare the variable like this:
var value = 10;
if(value == 10) {
console.log("Evaluate");
}

Variable scope Javascript [duplicate]

This question already has answers here:
Are variables declared with let or const hoisted?
(7 answers)
Closed 4 years ago.
var x = true;
if (x == true) {
console.log(typeof(x));
let x = false;
};
console.log(x);
Sorry new to programming and getting this error:
Error: x is not defined.
I am extremely confused.
It doesn't look like it, but the two variables you declared are different. Your var declaration is one of them, and the let declaration is different. You've confused yourself by naming them with the same variable.
The let x exists strictly within the if block. This let x is the only x that can exist in that block now and you've tried to use that x before you declared it when you attempt a console.log.
You can get away with using variables before you declare them with var, but let and const won't let you.
Also, I highly recommend you don't mix var and let in your code. You have to really understand what's going on if you do.
var x = true; // first x variable
if (x == true){ // first x variable
console.log(typeof(x)); // second x variable, used before declaration
let x = false; // second x variable created in `if` block
};
console.log(x); // first x variable
edit:
Your follow up question is still 2 different variables. The only thing you've done is coerced the code to make it look EVEN MORE like the same variable.
var x = true; // first x
if (x == true) { // first x
let x = false; // second x
console.log(x); // second x, false
};
console.log(x) // first x, true
This one's a little tricky to explain, but I'll try;
var x = true;
if (x == true) {
console.log(typeof(x)); // <-- Error: x is not defined.
let x = false;
};
console.log(x); // true
The last line is actually fine because you defined x up top.
What's happening inside the if statement is that JavaScript looks ahead and sees that you've declared x (with let or const) somewhere in that scope, but it hasn't yet reached that line.
So merely having a let or const somewhere further down in the same scope is causing that variable to not be defined.
If you move it up a line, everything is fine:
var x = true;
if (x == true) {
let x = false;
console.log(x); // false
};
console.log(x); // true
And if you don't redeclare x, it's also fine:
var x = true;
if (x == true) {
let y = false; // different variable name (won't "shadow" the `x` from above)
console.log(x,y); // true false
};
console.log(x); // true
var behaves differently:
if (true) {
console.log(y); // undefined
var y = false; // `var` is less strict. The declaration of `y` is hoisted to the top of the scope, but it's not assigned until this line
console.log(y); // false
};
The part of explanation that everyone is missing is that declarations are hoisted, which means that the declaration is brought to the beginning.
This is especially true with var. For let things are a little bit different and the term hoisting is not the most accurate. But it is useful to understand what is going on.
When executed, your code will look something like this (not exactly but gives the idea)
var x = true;
if (x == true) {
let x // hoisted at top of scope, for let scope is this if block
console.log(typeof(x));
x = false;
};
console.log(x);
Now everything should make sense: typeof(x) refers to the x declared with let but not yet initialized.
To be clearer this is the reason why the x inside of typeof refers to the x declared in the row below and not the one at the beginning: because the declaration of the existence of x inside that block is brough to the beginning of such block

Should a variable be declared before it is used as an argument in a function in Javascript?

Example:
var num;
function mySquare(num) {
var sq = num * num;
}
Is var num statement necessary or that statement can be neglected?
In you specific case, the statement var num; is useless. It won't even be used.
When you declare a function, the arguments represent local variables that are created specifically for the function block.
num is a local variable inside function mySquare so you can ignore var num;
function parameters will be declared and initialized before passing them into the function.
function a(helloWorld) {
console.log(helloWorld)
}
a("test") //test
var b = "hallo welt"
a(b) //hallo welt
a(c) //undefined
greetings
By specifying num as the name of an argument in the parameter list, you have already declared it as a local variable. Explicitly adding var num inside the function would be redundant and JSLint would warn you that you are redeclaring num if you tried.
Explicitly adding var num outside the function would create a global variable with the same name… that you never use. This is also redundant.

Defining variable within if statement in javascript

I want to assign a value to a variable when a condition is verified like this
if (k<12){
var Case=4;
}
The problem when i call this variable to be printed in the body of the page i get undefined
document.write(Case);
Basically your var statement gets hoisted and assigned with undefined.
Variable declarations, wherever they occur, are processed before any code is executed. The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global. If you re-declare a JavaScript variable, it will not lose its value.
Order of execution:
var Case; // hoisted, value: undefined
if (k < 12) {
Case = 4;
}
You are getting undefined because you have not actually defined it. You are defining it when the condition is true. You should write the code like this.
var Case = null;
var k = 0;
if(k > 14) {
Case = 3;
}
document.write(Case);
I hope it was helpful.
var Case = 0;
if(k<12){
Case = 4;
}
document.write(Case);
You need to define it first so if k<12 == False it wont be undefined.

Categories