javascript variable declaration in the if/else loop
You can just declare let hello=''
at the beginning of the code:
As let
variable have the scope inside the brackets of them { }
...
The let statement declares a block-scoped local variable, optionally
initializing it to a value.
Read More:
What's the difference between using "let" and "var"?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
var test = 4;
let hello = "";
if (test > 3) {
hello = "hello world";
} else {
hello = "hello gold";
}
console.log(hello);
JavaScript OR (||) variable assignment explanation
See short-circuit evaluation for the explanation. It's a common way of implementing these operators; it is not unique to JavaScript.
setting a javascript variable with an if statement -- should the 'var = x' be inside or outside the IF?
perfect use for a ternary
var B = (A ==="red") ? "hot":"cool";
Ternary expressions will always return the first value if true, the second value if not. Great for one-off if/else statements, but if you get into more nested conditions, be sure to use the traditional if/else blocks for readability.
Declaring multiple variables in JavaScript
The first way is easier to maintain. Each declaration is a single statement on a single line, so you can easily add, remove, and reorder the declarations.
With the second way, it is annoying to remove the first or last declaration because they start from the var
keyword and finish with the semicolon respectively. Every time you add a new declaration, you have to replace the semicolon in the last old line with a comma.
Defining JavaScript variables inside if-statements
As of the official release of ES2017 spec (2017-07-08), EcmaScript does support true block scope now using the let
or const
keywords.
Since ECMAscript doesn't have block scope but function scope, its a very good idea to declare any variable on the top of your function contexts.
Even though you can make variable and function declarations at any point within a function context, it's very confusing and brings some weird headaches if you aren't fully aware of the consequences.
Headache example:
var foo = 10;
function myfunc() {
if (foo > 0) {
var foo = 0;
alert('foo was greater than 0');
} else {
alert('wut?');
}
}
Guess what, we're getting a 'wut?' alert when calling myfunc
here. That is because an ECMAscript interpreter will hoist any var
statement and function declaration to the top of the context automatically. Basically, foo
gets initialized to undefined
before the first if statement
.
Further reading: JavaScript Scoping and Hoisting
Can I assign a variable to the result of an if statement in javascript?
Try using the ? operator.
var result = (someVariable === 2 ? something : (someOtherVariable ? somethingElse : null));
The operator works like this:
boolean ? result if true : result if false;
declaration for variable in while condition in javascript
The question is a little dated, but I think the answers all miss an important distinction. That is, a while
loop expects an expression that evaluates to a conditional, i.e., a boolean or value that can be converted to a boolean. See Mozilla docs for details.
A pure assignment (without instantiation) is coerced to a boolean via its default return value (the value of the right-hand-side).
A var
(or let
or const
) is a statement that allows an optional assignment but has a return value of undefined
.
You can easily test this in your console:
var foo = 42; // undefined
bar = 42 // 42
The return values alone don't answer the question, since undefined
is falsey, but does show that even if JS let you put a var
in a conditional it would simply always evaluate to false.
Others have mentioned for
statements and that they allow declaration and instantiation of variables. This is true, but the documentation explains that for
expects a statement or assigment.
Opinions may vary, but for me all this adds up to an understandable consistency not a quirk in behavior with regard to loops. A while
loop is better thought of as a looping version of an if
statement than akin to a for
loop. If there is quirkiness in all of this, it's the for
statement's wholesale divergence from the language's normal syntax.
Assign variable in if condition statement, good practice or not?
I wouldn't recommend it. The problem is, it looks like a common error where you try to compare values, but use a single =
instead of ==
or ===
. For example, when you see this:
if (value = someFunction()) {
...
}
you don't know if that's what they meant to do, or if they intended to write this:
if (value == someFunction()) {
...
}
If you really want to do the assignment in place, I would recommend doing an explicit comparison as well:
if ((value = someFunction()) === <whatever truthy value you are expecting>) {
...
}
Related Topics
Start a CSS Animation on Button Click
Css/Js for Circular Cropping of an Image
How to Prevent CSS Interference in an Injected Piece of HTML
Change Text Selection Highlight with Js
How to Hide Href Attribute of <A> Tag via CSS When Using Window.Print
Content Disappears Immediately After Form Submitted and Function Runs
Elements Positioned Relatively Don't Move When the Dom Is Updated (IE6 and IE7)
Iframe CSS Override for New Twitter Widget
JavaScript - Page Has to Be Refreshed to Show Particle-Slider Logo Effect
How to Display Select Options as Buttons
Laravel 8 + Nginx - App.CSS and App.Js Resources from Public/ Not Loading - 404 Not Found
Detect When Scrolling Has Finished When Using 'Scroll-Behavior: Smooth'
Fiill the Space Between Two Text Elements with Dots
How to Enable the JavaScript Error/Debug Console for Safari Within Android
Trigger a Click on a Different Element When Clicking an Other Div
Does Animating the Value of a CSS3 Transform with JavaScript Rule Out Hardware Acceleration