samedi 12 décembre 2020

false if statement executing console.log's [duplicate]

Prelude: Just starting to learn javascript so I apologize if this question has been answered else. I found similar titles but had a hard time reading the code. I'm trying to prevent past practice with code from logging to the console because it is cluttering up the console. I know I could just make a new document or even erase the code. But now that I've tried this and it isn't working, I'd like to know why for future use.

Problem: I set the variable (nameStuff) to 0 and yet the if statement runs as if the variable were a 1. I've tried changing the variable and the condition to different things without prevail. Thanks for your help and time!

let nameStuff = 0

let firstName = "   Taylor"
let lastName = "Waddell "
let fullName = firstName + " " + lastName
let fullNameLength = fullName.length
let noSpace = fullName.trim()
let fullNameCaps = noSpace.toUpperCase()

if (nameStuff = 1) {
  console.log(firstName)
  console.log(fullName)
  // console.log(fullName.length)
  console.log(fullNameLength)
  console.log("=====================")
  console.log(noSpace)
  console.log(fullNameCaps)
  console.log(noSpace.toLowerCase())

} else if (nameStuff = 0) {
  console.log("Name code is in hiding.")
}

Ended up doing this instead and it worked.

let nameStuff = false

let firstName = "   Taylor"
let lastName = "Waddell "
let fullName = firstName + " " + lastName
let fullNameLength = fullName.length
let noSpace = fullName.trim()
let fullNameCaps = noSpace.toUpperCase()

if (nameStuff) {
  console.log(firstName)
  console.log(fullName)
  // console.log(fullName.length)
  console.log(fullNameLength)
  console.log("=====================")
  console.log(noSpace)
  console.log(fullNameCaps)
  console.log(noSpace.toLowerCase())

} else {
  console.log("Name code is in hiding.")
}

But if possible, I would still love to know why the original code didn't work the way I expected. Thanks!

Aucun commentaire:

Enregistrer un commentaire