- 10 JavaScript If else exercises with solution
- 1. Check if a number is odd or even in JavaScript
- 2. Check if input variable is a number or not
- 3. Find the largest of two number
- 4. Find the largest of three number
- 5. Check if a triangle is equilateral, scalene, or isosceles
- 6. Find the a number is present in given range
- 7. Perform arithmetic operations on two numbers
- 8. Find check if a year is leap year or not
- 9. Find the grade for input marks
- 10. Find number of days in a given month
- Практическая задача — Несколько условий If Else
- Первый вариант решения задачи
- Второй вариант решения задачи
- Практическая задача — Условия JavaScript и конструкция if-Else
10 JavaScript If else exercises with solution
1. Check if a number is odd or even in JavaScript
Function `isEvenOrOdd()` checks if input number is even or odd by using “%” operator in JavaScript.
- Print “Number is even” if the number is divisible by 2.
- Else print “Number is odd” if the number returns a remainder when divided by 2.
function isEvenorOdd(num) < if(num % 2 == 0)< console.log(`$is a Even number`) > else < console.log(`$is a Odd number`) > > isEvenorOdd(10) //"10 is a Even number" isEvenorOdd(19) //"19 is a Odd number"
2. Check if input variable is a number or not
Function `isNumber()` checks if input variable is a number by using isNaN() in-built JavaScript function. Read more about isNan() from w3schools.com/jsref/jsref_isnan.asp.
- Print “Variable is not a number” if isNaN() returns true.
- Else print “Variable is a valid number” if isNaN() returns false.
function isValidNumber(num) < if(isNaN(num))< console.log(`$is not a number`) > else < console.log(`$is a valid number`) > > isValidNumber(11) //"11 is a valid number" isValidNumber("19") //"19 is a valid number" isValidNumber("xyz") //"xyz is not a number" isValidNumber("17.5") //"17.5 is a valid number" isValidNumber("21F") //"21F is not a number"
3. Find the largest of two number
Function `findLargest()` finds the largest between two number by using “>” and “=” operator in JavaScript.
function findLargest(num1, num2) < if(num1 >num2) < console.log(`$is the largest number`) > else if (num2 > num1) < console.log(`$the largest number`) > else < console.log(`$is equal to $`) > > findLargest(21,45) //"45 the largest number" findLargest(34,18) //"34 is the largest number" findLargest(41,41) //"41 is equal to 41"
4. Find the largest of three number
Function `findLargest()` finds the largest of three number by using “>” and “&&” operator in JavaScript.
function findLargest(num1, num2, num3) < if(num1 >num2 && num1 > num3) < console.log(`$is the largest number`) > else if (num2 > num3) < console.log(`$is the largest number`) > else < console.log(`$is the largest number`) > > findLargest(21,45,13) //"45 is the largest number" findLargest(34,18,52) //"52 is the largest number" findLargest(64,11,11) //"64 is the largest number"
5. Check if a triangle is equilateral, scalene, or isosceles
Function `findTriangleType()` finds the type of the triangle for given side values by using “==” and “&&” operator in JavaScript.
- Print “Equilateral triangle.” if values for all side1, side2 and side3 are equal.
- Print “Isosceles triangle.” if values for side1 is equal to side2 or side2 is equal to side3
- Else “Scalene triangle.” since values of all sides are unequal.
function findTriangleType(side1, side2, side3) < if((side1 == side2) && (side1 == side3))< console.log(`Equilateral triangle.`) >else if ((side1 == side2) || (side2 == side3) || (side1 == side3)) < console.log(`Isosceles triangle.`) >else < console.log(`Scalene triangle.`) >> findTriangleType(12,12,12) //"Equilateral triangle." findTriangleType(20,20,31) //"Isosceles triangle." findTriangleType(5,4,3) //"Scalene triangle."
6. Find the a number is present in given range
Function `checkInRange()` finds if the given number is within the provided start and end range using >=,
- Print “Between the range” if num is between start and end values
- Else Print “Outside the range” since num is outside start and end values.
function checkInRange(num, start, end) < if(num >= start && num is between the range $ and $`) > else < console.log(`$is outside the range $ and $`) > > checkInRange(15,11,30) //"15 is between the range 11 and 30" checkInRange(20,34,51) //"20 is outside the range 34 and 51"
7. Perform arithmetic operations on two numbers
Function `evalNumbers()` prints the result after evaluating arithmetic operations between two numbers of addition, multiplication, division, and modulus in JavaScript.
- Print result of num1+num2 if operation is “add”
- Print result of num1-num2 if operation is “subtract”
- Print result of num1*num2 if operation is “multiply”
- Print result of num1/num2 if operation is “divide”
- Print result of num1%num2 if operation is “modulus”
- Else print “Invalid operation”
function evalNumbers(num1, num2, op) < if(op == "add")< console.log(`Sum of $and $ is $`) > else if(op == "subtract") < console.log(`Difference of $and $ is $`) > else if(op == "multiply") < console.log(`Product of $and $ is $`) > else if(op == "divide") < console.log(`Division of $and $ is $`) > else if(op == "modulus") < console.log(`Modulus of $and $ is $`) > else < console.log(`$is an invalid operation`) > > evalNumbers(15,10,"add") //"Sum of 15 and 10 is 25" evalNumbers(20,8,"subtract") //"Difference of 20 and 8 is 12" evalNumbers(12,4,"multiply") //"Product of 12 and 4 is 48" evalNumbers(28,7,"divide") //"Division of 28 and 7 is 4" evalNumbers(22,3,"modulus") //"Modulus of 22 and 3 is 1" evalNumbers(31,3,"square") //"square is an invalid operation"
8. Find check if a year is leap year or not
Function `checkLeapYear()` find if the given year is a leap year or not by using %, !=, && and || operators in JavaScript.
- If year is divisble by 4 and not divisble by 100 then print “leap year”.
- Or if year is divisible by 400 then print “leap year”.
- Else print “not a leap year”.
function checkLeapYear(year) < if(((year%4 == 0)&&(year%100 != 0))||(year%400 == 0))< console.log(`Year $is a leap year`); > else < console.log(`Year $is not a leap year`); > > checkLeapYear(2012) //"Year 2012 is a leap year" checkLeapYear(1900) //"Year 1900 is not a leap year" checkLeapYear(2000) //"Year 2000 is a leap year" checkLeapYear(2011) //"Year 2011 is not a leap year"
9. Find the grade for input marks
- Print “S grade” if marks is between 90 and 100.
- Print “A grade” if marks is between 80 and 90.
- Print “B grade” if marks is between 70 and 80.
- Print “C grade” if marks is between 60 and 70.
- Print “D grade” if marks is between 50 and 60.
- Print “E grade” if marks is between 40 and 50.
- Print “Student has failed” if marks is between 0 and 40.
- Else print “Invalid marks”.
function findGrade(name, marks) < if(marks >= 90 && marks you have received S grade`) > else if(marks >= 80 && marks < 90)< console.log(`$you have received A grade`) > else if(marks >= 70 && marks < 80)< console.log(`$you have received B grade`) > else if(marks >= 60 && marks < 70)< console.log(`$you have received C grade`) > else if(marks >= 50 && marks < 60)< console.log(`$you have received D grade`) > else if(marks >= 40 && marks < 50)< console.log(`$you have received E grade`) > else if(marks >= 0 && marks <40)< console.log(`$you have Failed`) > else< console.log(`Invalid marks of $`) > > findGrade("John Doe", 91) //"John Doe you have received S grade" findGrade("John Doe", 85) //"John Doe you have received A grade" findGrade("John Doe", 73) //"John Doe you have received B grade" findGrade("John Doe", 53) //"John Doe you have received D grade" findGrade("John Doe", 20) //"John Doe you have Failed" findGrade("John Doe", 120) //"Invalid marks of 120"
10. Find number of days in a given month
Function `findDaysInMonth()` finds the number of days in a given month of a year.
- If month is outside the range of 1 and 12 print “Invalid month”.
- If month is equal to 2 ie, February print “29 days” if leap year else print “28 days” .
- Else if month is equal to 4, 6, 9 or 11 print “30 days”.
- Else print “31 days”.
function isLeapYear(year) < return (((year%4 == 0)&&(year%100 != 0))||(year%400 == 0)); >function findDaysInMonth(month, year) < if(month < 1 || month >12)< console.log(`Invalid Month of value $`) return; > if(month ==2) < if(isLeapYear(year))< console.log(`The Month has 29 days`) >else < console.log(`The Month has 28 days`) >> else if(month == 4 || month == 6 || month == 9 || month== 11) < console.log(`The Month has 30 days`) >else < console.log(`The Month has 31 days`) >> findDaysInMonth(2, 2012) //"The Month has 29 days" findDaysInMonth(2, 2013) //"The Month has 28 days" findDaysInMonth(4, 2012) //"The Month has 30 days' findDaysInMonth(10, 2013) //"The Month has 31 days"
Практическая задача — Несколько условий If Else
Самостоятельно выполните практическую задачу по реализации ситуации с несколькими условиями, используя операторы If и Else в JavaScript .
Нужно написать условие для действий пешехода при различных сигналах светофора.
Если сигнал красный, то надо стоять, иначе, если желтый — надо приготовиться, а иначе — можно идти.
Первый вариант решения задачи
Создаются переменные red и yellow для красного и жёлтого сигналов светофора соответственно.
В том случае, если переменным red или yellow присвоены значения «нет» , горит зелёный сигнал светофора и выводиться сообщение, разрешающее переходить дорогу.
var red = «нет» , yellow = «нет» ;
if (red == «да») /* Если горит красный сигнал */
<
document . write («При красном сигнале стоим — дорогу переходить нельзя!»);
>
else if(yellow == «да») /* Если горит жёлтый сигнал */
<
document . write («При жёлтом сигнале нужно приготовиться, но дорогу пока переходить нельзя!»);
>
else /* Иначе. */
<
document . write («Зелёный сигнал — переходим дорогу.»);
>
Зелёный сигнал — переходим дорогу.
Если же любой из переменных red или yellow присвоить значение «да» , то вы увидите одно из запрещающих сообщений. Это продемонстрировано в следующем примере.
var red = «нет» , yellow = «да» ;
if (red == «да») /* Если горит красный сигнал */
<
document . write («При красном сигнале стоим — дорогу переходить нельзя!»);
>
else if(yellow == «да») /* Если горит жёлтый сигнал */
<
document . write («При жёлтом сигнале нужно приготовиться, но дорогу пока переходить нельзя!»);
>
else /* Иначе. */
<
document . write («Зелёный сигнал — переходим дорогу. «);
>
При жёлтом сигнале нужно приготовиться, но дорогу пока переходить нельзя!
Второй вариант решения задачи
Создаётся переменная signal , от значения которой зависит действие, соответствующее определённому сигналу светофора.
var signal;
if (signal == «red») /* Если горит красный сигнал */
<
document . write («Идти нельзя!»);
>
else if(signal == «yellow») /* Если горит жёлтый сигнал */
<
document . write («Приготовиться. «);
>
else /* Иначе. */
<
document . write («Переходим дорогу»);
>
В примере переменной signal не присвоено значение, поэтому после прохождения цикла условий подразумевается, что горит зелёный сигнал светофора. И выполняется действие «Переходим дорогу».
Если переменной signal присвоить значение «red» или «yellow» , то мы увидим соответствующее сообщение.
var signal = «red» ;
if (signal == «red») /* Если горит красный сигнал */
<
document . write («Идти нельзя!»);
>
else if(signal == «yellow») /* Если горит жёлтый сигнал */
<
document . write («Приготовиться. «);
>
else /* Иначе. */
<
document . write («Переходим дорогу»);
>
Практическая задача — Условия JavaScript и конструкция if-Else
Практическая задача по заметкам введения в условия в Javascrip t и конструкция If-Else будет касаться также массивов.
Таким образом, две темы будут совмещены в одном задании.
Есть массив друзей: var friends = [«Алексей», «Вячеслав», «Григорий», «Настя», «Павел»] ;
Нужно написать условие, которое проверяет следующее : если количество элементов в массиве больше или равно 3, то выводится сообщение о том, что это большой массив, в котором как минимум 3 элемента. Иначе, следует вывести на экран сообщение о том, что это маленький массив, в котором менее 3-х элементов.
Для решения задачи необходимо знать о том, как посчитать число элементов массива. За это отвечает свойство length.
Далее, зная число элементов массива, можно легко написать проверочное условие.
var friends = [«Алексей», «Вячеслав», «Григорий», «Настя», «Павел»];
var count = friends.length; /* Создаём переменную count в которую заносим число элементов Массива friends */
if(count >= 3) /* создаём условие: если count больше или равно 3, то. */
document . write («Это большой массив, в котором как минимум 3 элемента»);
else /* иначе. */
<
document . write («Это маленький массив, в котором менее 3-х элементов»);
>
Это большой массив, в котором как минимум 3 элемента
Эту же задачу можно выполнить иначе , используя более короткий вариант записи кода. Переменную count , в которую заносится число элементов массива создавать не обязательно.
var friends = [«Алексей», «Вячеслав»];
if(friends.length >= 3) /* создаём условие: если число элементов массива friends больше или равно 3, то. */
document . write («Это большой массив, в котором как минимум 3 элемента»);
else /* иначе. */
<
document . write («Это маленький массив, в котором менее 3-х элементов»);
>
Это маленький массив, в котором менее 3-х элементов