Defining variable within if statement in javascript - 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.

Related

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

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.

What is the use of just declaring variables

I have been using python for a while now, and have just started learning javascript. In javascript you can, as I understand it, declare a variable without assigning a value to it (var cheese compared to var cheese = 4) in what situation would you want to declare a variable but not assign a value to it straight away?
Consider this snippet.
if (someCondition) {
var x = 5;
} else if (someOtherCondition) {
var x = 4;
}
if (x) {
doFunc();
}
Since x needs to exist for the doFunc to run, you simply add an undefined declaration above. var x; so that the if (x) doesn't return an error.
You do this when you want the value of the variable to be undefined.
var cheese;
console.log(cheese); // undefined
It's simpler than
var cheese = undefined;
The undefined value doesn't seem much useful, but this will allow to assign some other value later.
var cheese; can be perfectly useful (even if you never assign anything to it). Of course it's a shorter way to type var cheese = undefined;, but that's not the only reason…
Using var declares a local variable, and this has a nice property: it hides variables from parent scopes.
There's another part to your question:
If we're going to assign a value to var cheese anyway: why not assign immediately?.
Answer: it may be fine for your algorithm to return cheese without ever assigning anything to it — i.e. "undefined is valid".
Here's an example which illustrates how var hides variables from parent scopes:
var a = 3;
console.log(a); // prints 3; "a" is defined in this scope
function findEvenNumber(numbers) {
var a; // we declare this local variable, to ensure that we do _not_ refer to the variable that exists in the parent scope
numbers.forEach(function(number) {
if (number % 2 === 0) {
a = number;
}
});
return a; // if no even number was found, it returns undefined (because we never assigned anything to a)
}
findEvenNumber([1, 2]); // returns 2;
console.log(a); // prints 3; the "a" in this scope did not get overwritten by the function
Speculation: maybe the var cheese; syntax exists in ECMA to enable programmers to declare all variables at the beginning of their function. Such a convention was enforced by the C89 compiler, and some people grew fond of it.

Does the variable of the current element in a Javascript for-each loop need defined outside the loop?

The W3Schools example for a JS for-each loop (http://www.w3schools.com/js/js_loop_for.asp) is
var person = {fname:"John", lname:"Doe", age:25};
var text = "";
var x;
for (x in person) {
text += person[x];
}
and I'm wondering if there's any particular reason why x is defined outside of the loop if it's only used inside the loop in that particular example, or if that's necessary condition for defining a for-each loop, and if so, why?
This is(/was) an old convention, meant largely to indicate that x does not exist only inside the loop.
Declaring variables at the top of a function is not necessary and is variously encouraged/discouraged by different style tools. It can be convenient to group variable declarations in one place, but may increase the distance between declaration and use (generally considered a bad thing).
In JS, the var declaration works at function-scope, so variables are hoisted to the top of the nearest function and live for the duration of the function. See:
function foo() {
for (var i = 19; i > 0; --i) {
console.log(typeof i); // number
}
console.log(typeof i); // number
}
foo();
Because the variable is accessible throughout the function, it is declared at the start of the function (C used to require this).
ES6 has changed this with the let statement, which introduces the more common block-level scoping. With let, the variable is only available inside of the loop:
function foo() {
for (let i = 19; i > 0; --i) {
console.log(typeof i); // number
}
console.log(typeof i); // undefined
}

How to access value of the global variable in other function javascript

Here is one of the similar example
var global=0;
function somefunction()
{
global++;
}
var temp=global;
function somefunctiontwo()
{
var x=temp;
}
here I am getting x=0
I want x=1
how can I assign newly assigned value of global variable to x
Use an object as global variable; that will be assigned by reference instead of 'by value' as for the simple (number) type:
var global = { value: 0 };
var temp = global;
in function:
global.value++;
now is:
temp.value == 1
temp and global refer to two different variables. Assigning to global will not change the value in temp.
Simply change var x=temp to var x=global. It's not clear why you need an intermediate variable.
var global=0;
var temp;
function somefunction(){
global++;
}
function somefunctiontwo() {
var x=temp;
console.log(x);
}
somefunction();
temp=global;
somefunctiontwo();
This will give what you expect. Pay attention on how/where you call the functions.
Your structure seems a little off, not sure if this is for a reason we can't see... Will presume it is. Can have a function that resyncs the temp value to global.
function syncGlob(){
return temp = global;
}
Returns temp as well so you can call it when creating x.
var x = syncGlob();
You're setting the value of temp to global PRIOR to the on ready firing - at this point global is 0. If you increment global at on ready, temp already has a value of 0.
When you click somefunction2 and assign x the value of temp, temp has a value of 0, because at the time of temp initiation, global had a value of 0 NOT 1

Categories