if/else


Node.js

  1. const array = [1, 2]
  2. if (array) {
  3. console.log('array exists')
  4. }
  5. if (array.length === 2) {
  6. console.log('length is 2')
  7. } else if (array.length === 1) {
  8. console.log('length is 1')
  9. } else {
  10. console.log('length is other')
  11. }
  12. const isOddLength = array.length % 2 == 1 ? 'yes' : 'no'
  13. console.log(isOddLength)

Output

  1. array exists
  2. length is 2
  3. no

Go

  1. package main
  2. import "fmt"
  3. func main() {
  4. array := []byte{1, 2}
  5. if array != nil {
  6. fmt.Println("array exists")
  7. }
  8. if len(array) == 2 {
  9. fmt.Println("length is 2")
  10. } else if len(array) == 1 {
  11. fmt.Println("length is 1")
  12. } else {
  13. fmt.Println("length is other")
  14. }
  15. // closest thing to ternary operator
  16. isOddLength := "no"
  17. if len(array)%2 == 1 {
  18. isOddLength = "yes"
  19. }
  20. fmt.Println(isOddLength)
  21. }

Output

  1. array exists
  2. length is 2
  3. no