What is the use of variable declarations only

I have been using python for a while and have just started learning javascript. In javascript, you can, as I understand it, declare a variable without assigning a value to it ( var cheesecompared to var cheese = 4), in what situation do you want to declare a variable, but not immediately assign a value to it?

+4
source share
3 answers

Consider this snippet.

if (someCondition) {
    var x = 5;
} else if (someOtherCondition) {
    var x = 4;
}

if (x) {
    doFunc();
}

Since it xmust exist to run doFunc, you simply add the undefined declaration above. var x;so as if (x)not to return an error.

0
source

You do this when you want the value of a variable to be undefined.

var cheese;
console.log(cheese); // undefined
Run codeHide result

It is easier than

var cheese = undefined;

undefined , .

0

var cheese; ( ). , var cheese = undefined;, ...

var , : .

:

var cheese: ?.

Answer: it may be good that your algorithm returns cheesewithout assigning it anything, i.e. " undefinedis valid."

Here is an example that illustrates how to varhide variables from parent areas:

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: there may be syntax in ECMA var cheese;that allows programmers to declare all variables at the beginning of their function. This convention was applied by the C89 compiler , and some people loved it.

-1
source

Source: https://habr.com/ru/post/1666805/


All Articles