본문 바로가기

Programing/JavaScript

Truthy and Falsy Values in JavaScript

 

 

1
2
3
4
5
6
7
function logTruthiness (val) {
    if (val) {
        console.log("Truthy!");
    } else {
        console.log("Falsy.");
    }
}
cs

 

 

Truthy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Outputs: "Truthy!"
logTruthiness(true);
 
// Outputs: "Truthy!"
logTruthiness({});
 
// Outputs: "Truthy!"
logTruthiness([]);
 
// Outputs: "Truthy!"
logTruthiness("some string");
 
// Outputs: "Truthy!"
logTruthiness(3.14);
 
// Outputs: "Truthy!"
logTruthiness(new Date());
cs

 

Falsy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Outputs: "Falsy."
logTruthiness(false);
 
// Outputs: "Falsy."
logTruthiness(null);
 
// Outputs: "Falsy."
logTruthiness(undefined);
 
// Outputs: "Falsy."
logTruthiness(NaN);
 
// Outputs: "Falsy."
logTruthiness(0);
 
// Outputs: "Falsy."
logTruthiness("");
cs

 

Truthy Falsy 예문

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
function reportAttitude (person) {
    if (person.skepticism) {
        console.log(person.name +
                    " is skeptical about " +
                    person.skepticism);
    } else {
        console.log(person.name + " wants to believe.");
    }
}
 
var mulder = {
    name"Fox Mulder"
};
 
var scully = {
    name"Dana Scully",
    skepticism: "UFOs & conspiracy theories"
};
 
var frohikey = {
    name"Melvin Frohikey",
    skepticism: ""
};
 
// Outputs: "Fox Mulder wants to believe."
reportAttitude(mulder);
 
// Outputs: "Dana Scully is skeptical about UFOs and conspiracy theories."
reportAttitude(scully);
 
// Outputs: "Melvin Frohikey wants to believe."
reportAttitude(frohikey);
cs

 

출처 : http://adripofjavascript.com/blog/drips/truthy-and-falsy-values-in-javascript.html