Eric_B
Eric_B

Reputation: 149

Variable conditional not declaring as expected

I'm prob missing something simple but I don't understand why this returns "undefined" in each console.log when I'm declaring the variable immediately before the console.log

            var timer;
            var timerCalc = Math.random()*2000;

            if (timerCalc > 1000){
                timer === 1000;
                console.log(timer);
            } else if  (timerCalc < 100) {
                timer === 100;
                console.log(timer);
            } else {
                timer === timerCalc;
                console.log(timer + " = between 100 and 1000");
            }

Upvotes: 0

Views: 44

Answers (4)

Michel Hanna
Michel Hanna

Reputation: 157

You are checking on equality not assigning value

Upvotes: 0

abderrazzak mohamed
abderrazzak mohamed

Reputation: 36

var timer;

your variable is created but no value is associated it gonna be undefined

timer === 1000;

this condition is undefined === 1000 wich is false

console.log(timer);

no value is assinged to timer so it's gonna show undefined

Actually if you replace === (strict comparison) with = (assign) in your code the console.log will show 1000 in the first log and 100 in the second

Upvotes: 0

Deiv
Deiv

Reputation: 3097

=== is for checking equivalency, use a single = to assign the variable.

So for example:

timer = 1000;
console.log(timer);  //will print out 1000

Upvotes: 2

Omri Aharon
Omri Aharon

Reputation: 17064

You're doing === (comparison) instead of = (assignment). Use the latter.

Upvotes: 4

Related Questions