DEV Community

Cover image for (Javascript) My learning journey: String and more
Eric The Coder
Eric The Coder

Posted on • Updated on

(Javascript) My learning journey: String and more

An essential point to remember a training course is to take notes and discuss the subject with others. That's why every day I will post on dev.to the concepts and notes that I learned the day before.

If you want to miss nothing click follow and you are welcome to comments and discuss with me.

Without further ado here is a summary of my notes for today.

String

const name = 'Mike Taylor'
// direct character access
console.log(name[0]) // M

// Get position (zero base)
console.log(name.indexOf('T')) // 5

// Modify one element
name[0] = 'P' // Pike Taylor

// Extract (slice) part or a string (start, stop before)
console.log(name.slice(5)) // Taylor
console.log(name.slice(5, 8)) // Tay
console.log(name.slice(-2)) // or

// Convert to lower or upper case
console.log(name.toLowerCase()) // mike taylor
console.log(name.toUpperCase()) // MIKE TAYLOR

// Remove white space
const title = ' This is a title with space   '
console.log(title.trim()) // 'This is a title with space'

// Chaining string method
console.log(title.toLowerCase().trim()) // 'this is a title with space'

// replace
const name = 'Mike Taylor'
console.log(name.replace('Mike', 'Paul') // Paul Taylor

// includes?
const name = 'Mike Taylor'
console.log(name.includes('Mike')) // true

// Split
const colors = 'Red, Green, Blue')
console.log(colors.split(',')) // ['Red', 'Green', 'Blue']

// Join
const colors = ['Red', 'Green', 'Blue']
const colors_string = colors.join('-') // Red-Green-Blue

Enter fullscreen mode Exit fullscreen mode

Short-circuit || operator

// if first value truthy then return first value
// if first value falsy then return second value 
console.log('Hello' || 'Hi') // 'Hello'
console.log('' || 'Bye') // 'Bye'
console.log('' || 0 || 100) // 100

// Assignment example
const maxUser = config.maxUser || 10

Enter fullscreen mode Exit fullscreen mode

Nullish Coalescing operator

// Only assign if null or undefined
const maxUser = config.maxUser ?? 10

Enter fullscreen mode Exit fullscreen mode

Optional chaining

if (customer.creditLimit) {
  if (customer.creditLimit.dateExpire) {
    console.log(customer.creditLimit.dateExpire)
  }
}
console.log(customer.creditLimit.dateExpire) // error
// optional chaining: assign only if not undefined or null
console.log(customer.creditLimit?.dateExpire) // undefined

Enter fullscreen mode Exit fullscreen mode

Top comments (0)