@jgCarroll/

logNumberFunction

JavaScript

A common interview question

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
var num = 50;
 
function logNumber() {
    console.log(num);
    var num = 100;
}
 
logNumber();

// ==============================

// because of hoisting, JavaScript interprets the code above like this (below). Because the variable declaration is now function scoped, it is interpreted by the console.log as being undefined

var num = 50;
 
function logNumber() {
    var num;
    console.log(num);
    num = 100;
}
 
logNumber();

// ==============================

// If I do this (below), the value 50 is logged.

var num = 50;
 
function logNumber() {
    console.log(num);
    num = 100;
}
 
logNumber();

// ==================================

// If I do this (below), the value 100 is logged.

var num = 50;
 
function logNumber() {
    num = 100;
    console.log(num);
}
 
logNumber();
Native Browser JavaScript