Null and '' difference

Hi,

I wanted to know what is the difference the following line of code
let a = ‘’;
let b = null;

I know the typeof operator returns string for ‘a’ and object for ‘b’ but i have seen code where it is written like while asking for input from the user and sort

if(a === ‘’ && b === null) {}

can someone give an example and explain this please. Thanks.

Hello again @Harshit_Badolla.

As I understand it, '' is an empty string value, whereas null is an absense of any value. You’ll meet them in different contexts.

So for example, you might want to check whether a text field has a value filled in or not, and react accordingly, so something like:

if(textInput.value = '') {
  alert('The name field is empty. Did you mean to include a name?');
}

You’ll most commonly come across null when you try to grab a reference to something but it doesn’t exist. For example let’s say you want to print out the number of news articles in the headlines container on your site, or report that there are no news articles if none are shown. You could maybe do something like:

if (document.querySelector('.headlines .story') === null) {
  console.log(`There are no news stories to read today.`);
} else {
  let storyCount = document.querySelectorAll('.headlines .story').length;
  console.log(`There are ${ storyCount } news stories to read today.`);
}

Does that help?

1 Like

Hello Chris,

why can’t i just enter the condition in the if statement like this
if (document.querySelector(’.headlines .story’) === ‘’) {
doSomething();
};

@Harshit_Badolla because when document.querySelector() doesn’t find any elements that match the selector you give to it as a parameter, it returns null, because there is no value available. It doesn’t return an empty string.

1 Like

Alright, I think I understand now. It will be more clear when I use it in a project. Thanks again.

in the ‘’ case it’s like you created string object and it’s value is empty and it has address in memory but in the null case the object does not point to any location in memory

hope that make it clear and have a nice day :slight_smile: