JavaScript Basics - Exercise 4
The comparison should include the boundary value when the exercise says “60 or more.” Store the result in a clear condition so changing the marks immediately changes the output.
let marks = 59;
if (marks > 60) {
console.log("Pass");
} else {
console.log("Fail");
}
//using ternary operator
marks > 60 ? console.log("Pass") : console.log("Fail");
The modulo operator returns the remainder after division by two. Both numbers must have a remainder of one for the “both odd” branch to run.
let num = 35;
let num2 = 34;
if (num % 2 === 1 && num2 % 2 === 1) {
console.log("Odd");
} else {
console.log("Even");
}
Assignment happens from left to right, so each value is replaced before the next assignment runs. The final line demonstrates why the original value of a is used for d.
/*
a = b
b = c
c = d
d = a*/
let a = 10;
let b = 20;
let c = 30;
let d = 40;
a = b; //a=20, b=20, c=30, d=40
b = c; //a=20, b=30, c=30, d=40
c = d; //a=20, b=30, c=40, d=40
d = a; //a=20, b=30, c=40, d=20
console.log(a, b, c, d); //20 30 40 20
Comments document intent for people reading the program and are ignored during execution. Use // for a line and /* ... */ for a block.
Comments are used to explain code and make it more readable. They are ignored by the JavaScript engine. Single-line comments use // and multi-line comments use /* */.
A number is odd when dividing it by two leaves a non-zero remainder. The condition below prints “Yes” only for odd values.
let num = 35;
if (num % 2 !== 0) {
console.log("Yes");
} else {
console.log("No");
}
A number divisible by both 10 and 5 must have a remainder of zero for both checks. Checking both conditions makes the requirement explicit and easy to change.
let num = 60;
if (num % 10 === 0 && num % 5 === 0) {
console.log("Yes");
} else {
console.log("No");
}
Instead of guessing the input, compare the product directly with 100. This keeps the condition readable and makes the “Yes” branch run only for the correct value.
let num = 5;
if (num * 20 === 100) {
console.log("Yes");
} else {
console.log("No");
}
Calculate the percentage from the earned marks and the total marks before comparing it with 70. This works even when the total changes from 1000 to another value.
let marks = 880;
let totalMarks = 1000;
let percentage = (marks / totalMarks) * 100;
if (percentage > 70) {
console.log("Pass");
} else {
console.log("Fail");
}
This example treats ages greater than 21 as adults, exactly as the question specifies. Change age to test both branches of the condition.
let age = 25;
if (age > 21) {
console.log("Adult");
} else {
console.log("Minor");
}
A ternary expression is a compact replacement for a simple two-branch if statement. Put the condition first, then the true result, followed by the false result.
// if-else solution
if (condition) {
// code block for true condition
} else {
// code block for false condition
}
// ternary operator solution
condition ? trueBlock : falseBlock;