Node.js - Getting Started with if else statements

by
Jeremy Canfield |
Updated: January 26 2025
| Node.js articles
An if statement in Node.js has the following structure.
if (condition) {
<do something>
} else if (condition) {
<do something>
} else {
<do something>
}
For example.
const foo = "Hello";
if (foo == "Hello") {
console.log("foo equals Hello");
} else if (foo == "World") {
console.log("foo equals World");
} else {
console.log("foo does not equal Hello or World");
}
If the "foo" var (variable) or const (constant) is defined
if (typeof foo === 'undefined') {
console.log("foo is undefined")
} else {
console.log(`foo is defined and is a ${typeof foo}`)
}
If the foo var (variable) or const (constant) contains a value
if (foo.length === 0) {
console.log("foo is empty (contains no value)")
} else {
console.log(`foo = ${foo}`)
}
If the foo var (variable) or const (constant) contains "hello"
const foo = "Hello World"
if (foo.toLowerCase().includes('hello')) {
console.log(`${foo} includes hello`)
} else {
console.log(`${foo} does NOT include hello`)
}
If the foo var (variable) or const (constant) contains "hello" or "world"
const foo = "Hello World"
if (/hello|world/.test(foo.toLowerCase())) {
console.log(`${foo} includes hello or world`)
} else {
console.log(`${foo} does NOT include hello or world`)
}
If the foo var (variable) or const (constant) is greater than or equal to or less than or equal to
if (foo > 100) {
console.log(`${foo} is greater than 100`)
} else {
console.log(`${foo} is less than 100`)
}
if (foo >= 100) {
console.log(`${foo} is greater than or equal to 100`)
} else {
console.log(`${foo} is less than 100`)
}
if (foo < 100) {
console.log(`${foo} is less than 100`)
} else {
console.log(`${foo} is greater than 100`)
}
if (foo <= 100) {
console.log(`${foo} is less than or equal to 100`)
} else {
console.log(`${foo} is greater than 100`)
}
Here is how you can string together two (or more) if statements.
if ((foo > 100) && (foo < 100)) {
console.log(`${foo} is greater than 100 and less than 200`)
} else {
console.log(`${foo} is less than 100 or greater than 200`)
}
If the /tmp/foo.txt file exists
import fs from "fs"
fs.readFile('/tmp/foo.txt', (err, data) => {
if (!err && data) {
console.log(data)
} else {
console.error(err)
}
})
Did you find this article helpful?
If so, consider buying me a coffee over at