Skip to main content

Conditions


  • if
  • else
  • else if

=== showing up as 3 lines is called a ligature and is just a font change of showing what === does. Don't use a double equal when comparing items together. Use the triple equal.

Others: image.png

Quick explanation


function canVote(age) {
if(age >=18) {
return true;
} else {
return false;
}
}

console.log(canVote(25)); // true
console.log(canVote(18)); // true
console.log(canVote(10)); // false

Early Returns and no else statement.


THis code doesn't necessarily need the else return false because when a return statement is hit, the script execution stops.

function canVote(age) {
if(age >=18) {
return true;
} else {
return false;
}
}

//becomes
function canVote(age) {
if(age >=18) {
return true;
}
return false;
}

Equals operator to check for a string


Gotta check for the empty string first...

/**
* @param {string} age
*/
export function getNextAge(age) {
if(age === "") {
return 0;
}
if(age >= 0) {
return parseInt(age,10) + 1;
}

}

Return a string with ellipsis


/**
* @param {string} text
*/
export function getDescription(text) {
if(text.length <=10)
{
return text;
}else {
return(text.substring(0,10) + "...");
}
}

// A more concise way to write it is to check the string if it is larger than 10, then, if it is, add the ellipsis. No else is needed, you can just return the original string if the string is not greater than 10

export function getDescription(text) {
if (text.length > 10) {
return text.substring(0, 10) + "...";
}
return text;
}

Return booleans


Sometimes you don't even need if then statements. Teke the canVote example above

function canVote(age) {
return age >= 18;
}

Even or odd?


Review


  • Using an if condition, you can run a piece of code when the condition evaluates to true
  • The syntax is if (condition) and then curly braces wrap the lines of code that correspond to this condition
  • The else keyword can be used to perform some other code based on all the other conditions not satisfied with the if.
  • When you have an if/else condition that returns two different results, it is possible to drop the else keyword.
  • Always use triple equals (===) when comparing 2 values in JavaScript.