-1

This is the JavaScript code.

function loadProfiles(usernames){
    if(usernames.length>3){
        var wmsg='This might take a while';
    }
    else{
        var imsg="Just a sec";
    }
    console.log(imsg);
}
loadProfiles(['Dinesh','Saratha','Sundhararasu']);

when i try to console wmsg it gives undefined

when i try to console imsg it gives just a sec but expected output is undefined.

what is the reason?

Dinesh S
  • 139
  • 2
  • 13
  • 2
    because it is undefined. because length is **NOT** > 3 - the length of your array is **THREE** ... a number can not be greater than itself (there's something almost spiritual in that statement) - note: why are you using two different variables to hold some message? why not just have msg= one or the other message? – Jaromanda X May 23 '18 at 05:00
  • Bro I'm learning javascript. In that concept var declared within the {} can be accessed outside with `undefined` value.I tried to execute that concept. In above example i want to know that why `imsg` print that msg outside the {} block. – Dinesh S May 23 '18 at 06:27
  • 1
    You've mixed up variable scope with hoisting. You get undefined only if you try to access the variable before a value has assigned to it. See [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – JJJ May 23 '18 at 06:31

2 Answers2

0

Try this instead:

function loadProfiles(usernames){
    if(usernames.length >= 3){
        var wmsg='This might take a while';
    }
    else{
        var imsg="Just a sec";
    }
    console.log(wmsg);
}
loadProfiles(['Dinesh','Saratha','Sundhararasu']);

Note the use of the "greater than or equal to" operator >= on line 2.

pcgben
  • 726
  • 7
  • 24
0

The console.log returns undefined because the condition in the if statement is not satisfied so the variable wmsg doesn't get initialized to the string 'This might take a while' but is rather set to the value undefined.

ekbgh
  • 36
  • 3
  • Bro when i try to print `imsg` it should print `just a sec` but why it gives me `undefined`. – Dinesh S May 23 '18 at 06:30
  • According to the code you posted above, the if block gets executed when the array length is greater than 3, setting variable wmsg to 'This might take a while'. If the array length is not greater than 3, the if block gets ignore, leaving the variable wmsg as undefined and executing the else clause. The else clause gets executed when the array length is not greater than 3. When the else clause gets executed, the imsg variable gets set to the value "Just a sec". Hope this helps – ekbgh May 23 '18 at 07:12