3-28 Default values

  • || operator will return first one could be coerced to true or false
js default value 小技巧
1
2
3
4
5
6
7
8
9
10
11
12
13

function greet(name){
console.log('Hello ' + name);
}

greet(); // 'Hello undefined'

function greet2(name){
name = name || '<Your name here>'
console.log('Hello ' + name);
}

greet2(); // 'Hello <Your name here>'

3-29 Framework aside: Default value

lib1.js
1
2

var libname = 'lib1';
lib2.js
1
2
3
4
5

var libname = 'lib2';

// batter way
// window.libname = window.libname || 'lib2';
app.js
1
2
3

console.log(libname);
//lib2
index.html
1
2
3
4
5
6
7
8
9
10
11
12

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script src = lib1.js type="text/javascript"></script>
<script src = lib2.js type="text/javascript"></script>
<script src = app.js type="text/javascript"></script>
</body>
</html>