JavaScript Crash Course for Beginners-4

Welcome to part-4 of the series. You can find part-3 here.

The first conditional which we are going to check is the if statement. The statement within the curly brackets will execute only if the condition is true.

We compare two things in JavaScript with the == operator.

const x = '10';if(x == 10){
console.log('x is 10');
}

So, here the console.log statement will be printed. But there is a problem in the above statement because x is string 10 and we are comparing it with numeric 10. Both are becoming equal because JavaScript changes the type of string to number before comparing.

We can solve this by using === operator, which does strict comparison and doesn’t changes the type of operands.

The below statement also shows a if-else statement, in which the else part will run when the if part is false.

const y = '20';
if(y === 20){
console.log('y is 20');
} else {
console.log('y is string 20');
}

We can see both above statements in action in the below jsbin.

Image for post
Image for post
if and if-else

Written by

UI Lead- ReactJS, JavaScript and everything in-between.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store