How to check if a String is empty in Javascript?

10

Given the following object:

var pessoa = {
      nome: "fernando"
}

Note: sometimes I'm getting the object as follows:

var pessoa = {
      nome: ""
}

How do I check if the name attribute is empty, as the second object shows?

    
asked by anonymous 23.12.2016 / 14:31

3 answers

17

I consider the most practical way:

if (!pessoa.nome)

You will see:

  • vazio ("")
  • null
  • NaN
  • undefined
  • false
  • 0

var pessoa = {
      nome: ""
}

if (!pessoa.nome)
  console.log("Atributo vazio");
    
23.12.2016 / 14:34
4

There are three ways to check this out.

if (pessoa.nome === "") {}

or

if (!pessoa.nome) {}

or

if (pessoa.nome.length === 0) {}

    
23.12.2016 / 14:34
3

Length checks how many characters it has.

if(pessoa.nome.length == 0)

If you have 0, that's why it's empty.

Or you can use exclamation ! to check if it is false, if it is true is why it always has characters.

Example

var pessoa = {
  nome_1 : 'Teste',
  nome_2 : ''
};

if(pessoa.nome_1.length == 0) console.log('Vazio');
if(pessoa.nome_2.length == 0) console.log('Vazio');

if(!pessoa.nome_1.length) console.log('Vazio');    
if(!pessoa.nome_2.length) console.log('Vazio');
    
23.12.2016 / 14:33