-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path025-string.js
More file actions
79 lines (59 loc) · 1.84 KB
/
025-string.js
File metadata and controls
79 lines (59 loc) · 1.84 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// 1: WHAT ARE STRINGS?
"Hello"
'JavaScript'
"A"
"12345"
"Hello, my name is John and I'm learning JavaScript!"
// let str1 = "Hello World";
// let str2 = 'Hello World';
// let str3 = `Hello World`;
// 2: STRING LITERALS
let firstName = "John";
let lastName = 'Doe';
let greeting = `Hello there!`;
let city = "New York";
let country = 'USA';
let message = "Welcome to JavaScript programming!";
let emptyString = "";
// 3: STRING CONSTRUCTOR
// let str1 = new String("Hello");
// let str2 = new String('World');
let literal = "Hello";
let constructor = new String("Hello");
console.log(typeof literal); // "string"
console.log(typeof constructor); // "object"
let str1 = "Hello";
let str2 = "Hello";
let str3 = new String("Hello");
let str4 = new String("Hello");
console.log(str1 === str2); // true
console.log(str3 === str4); // false
// 4: WHY USE LITERALS?
// 5: PRIMITIVE WRAPPER
// let name = "John";
// console.log(name.toUpperCase()); // "JOHN"
// What you write:
// let name = "John";
// name.toUpperCase();
// // What JavaScript does behind the scenes:
// let name = "John";
// (new String(name)).toUpperCase();
// 6: PRACTICAL EXAMPLES
// String literals (recommended)
let username = "coder123";
let email = 'user@example.com';
let bio = `JavaScript developer learning every day`;
// These are all string primitives
console.log(typeof username); // "string"
console.log(typeof email); // "string"
console.log(typeof bio); // "string"
// We can still use methods on them
console.log(username.length); // 8
console.log(email.toUpperCase()); // "USER@EXAMPLE.COM"
console.log(bio.includes("JavaScript")); // true
// Don't do this
let wrongWay = new String("Hello");
console.log(typeof wrongWay); // "object" - not what we want!
// Do this instead
let rightWay = "Hello";
console.log(typeof rightWay); // "string" - perfect!