Mündəricat
Javascript varsa-başqa
Şərti ifadələr hər hansı bir proqramın əsas təməl daşlarıdır. Şərt doğrudursa, müəyyən edilmiş ifadələrə əməl edin, əks halda başqa bir sıra təyin edilmiş ifadələrə əməl edin. Bütün proqramlaşdırma dilləri kimi Javascript də bunun üçün öz sintaksisinə malikdir.
if (condition){ statement1; //These statements will be executed when condition is true statement2; } else{ statement1; //These statements will be executed when condition is false statement2; }
Birdən çox şərti yoxlamaq istəsək və ya fərqli şərtlərə görə çoxlu hesabat yazmaq istəsək.
if (condition1) statement1; else if (condition2) statement2; else if (condition3) statement3; else statement4;
Tək bir bəyanat yazırıqsa, onu parantez içərisinə salmağa ehtiyac yoxdur.
if (condition1 && condition2) statement1; else if (condition3 && condition4) statement2; else if (condition5) statement3; else statement4;
Məntiqi operatorlardan bu şəkildə istifadə ediləcək.
Nümunələri başa düşmək olduqca çətindir, lakin real həyat nümunəsi ilə əlaqələndirildikdə onları başa düşmək sadədir.
var age = 19; if (age<18) console.log("Not eligible to vote"); else console.log("Eligible to vote");
console.log () brauzer konsolunda yazdırmaq üçün bir funksiyadır. Bu kodda bir səhv var. Tapa bilər və həll edə bilərsən ->
var age = 19; var gender = 'M'; if ((age<18) && (gender==='M')) console.log("You are less than 18 and a male"); else if ((age>=18) && (gender==='M')) console.log("You are 18 or more and a male"); else ((age<18) && (gender!=='M')) console.log("You are less than 18 and a female"); else console.log("You are 18 or more and a female");
İç içə şərti ifadələr
var age = 19; var gender = 'M'; if (age<18){ if(gender==='M'){ console.log("You are less than 18 and a male"); } else{ console.log("You are less than 18 and a female"); } } else{ if(gender==='M'){ console.log("You are 18 or more and a male"); } else{ console.log("You are 18 or more and a female"); } }
tapşırıq
- Üçbucağın bərabər tərəfli, izosel və ya skalenin bütün üç tərəfi verildiyini yoxlamaq üçün bir şərt yazın.
- 5 fənnin orta qiymətlərini yoxlamaq və müvafiq olaraq qiymət vermək üçün bir şərt yazın.
- Orta qiymət> = 85 olduqda A dərəcəsi
- Orta qiymət> = 65 və <85 olarsa B dərəcəsi
- Orta qiymət> = 45 və <65 olduqda C dərəcəsi
- Əks halda D dərəcəsi
Solutions
var sideA; var sideB; var sideC; if(sideA===sideB && sideB===sideC) console.log("Equilateral"); else if(sideA===sideB || sideB===sideC || sideC===sideA) console.log("Isoceles"); else console.log("Scalene");