Why JAVASCRIPT?
How to write and run Javascript
How to Add Javascript to Webpage
Representing data with values
Primitive Data Types
- Primitive Data Types
- Number Type
- String Type
- Boolean data type
- Undefined and null
- JavaScript Type Conversions
Operators
Expressions
Statements
- What are statements?
- Expression Statements
- Compound and Empty Statements
- Declaration Statements
- Conditional statements
- Loop statements
- Jump Statements
- Assignments
Arrays
Conditional statements execute or skip other statements depending on the value of a specified expression.
These statements are the decision points of your code, and they are also sometimes known as “branches” or “blocks”. If you imagine a JavaScript interpreter following a path through your code, the conditional statements are the places where the code branches into two or more paths and the interpreter must choose which path to follow.
if statement
The if statement is the fundamental control statement that allows JavaScript to make decisions, or, more precisely, to execute statements conditionally. This statement has two forms. The first is:
if (expression)
statement
In this form, expression is evaluated. If the resulting value is truthy, statement is executed. If expression is falsy, statement is not executed.
For example:
if (username == null) // If username is null or undefined,
username = "John Doe"; // define it
Or similarly:
// If username is null, undefined, false, 0, "", or NaN, give it a new value
if (!username) username = "John Doe";
Note that the parentheses around the expression are a required part of the syntax for the if statement. JavaScript syntax requires a single statement after the if keyword and parenthesized expression, but you can use a statement block to combine multiple statements into one. So the if statement might also look like this:
if (!address) {
address = "";
message = "Please specify a mailing address.";
}
The second form of the if statement introduces an else clause that is executed when expression is false.
Its syntax is:
if (expression)
statement1
else
statement2
This form of the statement executes statement1 if expression is truthy and executes statement2 if expression is falsy.
For example:
if (n == 1)
console.log("You have 1 new message.");
else
console.log("You have " + n + " new messages.");
When you have nested if statements with else clauses, some caution is required to ensure that the else clause goes with the appropriate if statement. Consider the following lines:
i = j = 1;
k = 2;
if (i == j)
if (j == k)
console.log("i equals k");
else
console.log("i doesn't equal j"); // WRONG!!
In this example, the inner if statement forms the single statement allowed by the syntax of the outer if statement. Unfortunately, it is not clear (except from the hint given by the indentation) which if the else goes with. And in this example, the indentation is wrong, because a JavaScript interpreter actually interprets the previous example as:
if (i == j) {
if (j == k)
console.log("i equals k");
else
console.log("i doesn't equal j"); // OOPS!
}
switch statement
An if statement causes a branch in the flow of a program’s execution, and you can use the else if idiom to perform a multiway branch.
This is not the best solution, however, when all of the branches depend on the value of the same expression. In this case, it is wasteful to repeatedly evaluate that expression in multiple if statements. The switch statement handles exactly this situation. The switch keyword is followed by an expression in parentheses and a block of code in curly braces:
switch(expression) {
statements
}
However, the full syntax of a switch statement is more complex than this. Various locations in the block of code are labeled with the case keyword followed by an expression and a colon.
case is like a labeled statement, except that instead of giving the labeled statement a name, it associates an expression with the statement. When a switch executes, it computes the value of expression and then looks for a case label whose expression evaluates to the same value (where sameness is determined by the === operator). If it finds one, it starts executing the block of code at the statement labeled by the case. If it does not find a case with a matching value, it looks for a statement labeled default:. If there is no default: label, the switch statement skips the block of code altogether.
The following switch statement is equivalent to the repeated if/else statements shown in the previous section:
switch(n) {
case 1: // Start here if n == 1
// Execute code block #1.
break;
// Stop here
case 2: // Start here if n == 2
// Execute code block #2.
break; // Stop here
case 3: // Start here if n == 3
// Execute code block #3.
break; // Stop here
default: // If all else fails...
// Execute code block #4.
break; // stop here
}
The break statement, described later in this chapter, causes the interpreter to jump to the end (or “break out”) of the switch statement and continue with the statement that follows it.
The case clauses in a switch statement specify only the starting point of the desired code; they do not specify any ending point. In the absence of break statements, a switch statement begins executing its block of code at the case label that matches the value of its expression and continues executing statements until it reaches the end of the block.
Examples
Write a program to check whether two numbers are equal or not.
Suppose, we need to check whether 0 is equal to 00 or not. To check this, we need to use comparison operators like == or ===. The == or equality operator will check only for value comparison whereas === or strict equality operator will check for value as well as data type comparison. So, it is advisable to use === operator for safety.
First, we declare two variables to store the 0 and 00.
var x = 0;
var y = 00;
To check the equality, we use an if condition, where we specify the condition, which in this case is x===y.
if(x===y) {
. . .
}
Now, according to our wish, we can state what we want to do if the numbers are equal or not. For example, we can print ‘Yes’ if they are equal and ‘No’ if they are not equal.
if(x===y) {
console.log("Yes");
}
else {
console.log("No");
}
Write a program to check whether a number is greater than 10 or not.
To check whether a number is greater than 10 or not, we can use the > (greater than) comparison operator. We can specify the condition in the if condition as follows:
var x = 25;
if(x>10) {
console.log('It is greater than 10');
}
else {
console.log('It is not greater than 10');
}
Write a program to check whether a number is positive or negative.
To check whether a number is positive or negative, we need to check whether the number is greater than 0 or not. If it is greater than 0, it is a positive number. Otherwise, it is a negative number.
var x = 5;
if(x>0) {
console.log('It is a positive number');
}
else {
console.log('It is not a positive number');
}
Write a program to check whether a number when divided by 10 gives remainder as 0 or not.
To get the remainder of division, we need to use the % (modulus) operator. To check whether a number when divided by 10 gives remainder as 0 or not, we need to check whether the modulus of the number by 10 gives 0 or not.
var x = 36;
if(x%10===0) {
console.log('It gives remainder as 0');
}
else {
console.log('It does not give remainder as 0');
}
Write a program to check whether a number is even or odd.
To check whether a number is even or odd, we have to check whether a number is divisible by 2 or not. To check whether a number is divisible by 2 or not, we have to check whether the number when divided by 2, gives 0 as remainder or not. If it gives 0 as remainder, it is divisible by 2, or else not.
var x = 58;
if(x%2===0) {
console.log('It is an even number');
}
else {
console.log('It is an odd number');
}
Write a program to check whether a number is divisible by 7 or not.
To check whether a number is divisible by 7 or not, we need to check whether the number when divided by 7 gives 0 as remainder or not. If it gives 0 as remainder, it is divisible by 7, or else not.
var x = 56;
if(x%7===0) {
console.log('It is divisible by 7');
}
else {
console.log('It is not divisible by 7');
}
Write a program to check whether a number is a multiple of 25 or not.
To check whether a number is multiple of 25 or not, we need to check whether the number when divided by 25, gives 0 as remainder or not.
var x = 200;
if(x%25===0) {
console.log('It is a multiple of 25');
}
else {
console.log('It is not a multiple of 25');
}
Write a program to check whether 84 is a multiple of the given number.
To check whether 84 is a multiple of a number, we need to check whether 84 when divided by the given number, gives 0 as remainder or not.
var x = 42;
if(84%x===0) {
console.log('84 is a multiple of the given number');
}
else {
console.log('84 is not a multiple of the given number');
}
Write a program to take the marks of three subjects as input and print the grade of the student according to the percentage obtained.
var x,y,z;
x = +prompt("enter the maths marks out of 100");
y = +prompt("enter the science marks out of 100");
z = +prompt("enter the social marks out of 100");
var percentage = (x+y+z)/3;
if(percentage>=70){
console.log("You passed with Distinction");
}
else{
if(percentage>=60){
console.log("You passed with First Class");
}
else{
if(percentage>=50){
console.log("You passed with Second Class");
}
else{
if(percentage>=40){
console.log("You passed with Third Class");
}
else{
console.log("Dont worry, Try again");
}
}
}
}
Write a program to take a number(using prompt) from 1 to 5 as input and print it in words.
Here, the objective is to take a number between 1 and 5 and print it in words. For example, if the input number is 3, then the output should be ‘three’. For this, we have to use multiple conditions as follows:
- If input is 1, the output should be ‘one’.
- If input is 2, the output should be ‘two’.
- If input is 3, the output should be ‘three’.
- If input is 4, the output should be ‘four’.
- If input is 5, the output should be ‘five’.
This can be achieved with switch statement. Moreover, the input is to be taken with prompt.
Prompt can be used as follows:
var x = prompt('Enter a number');
Here, x will hold the value that we pass to the prompt box. But whatever input we give to prompt is taken as string. For example, if we provide 1 as input, it will be stored as ‘1’ in the variable x. So, we need to convert the value to number. For this, we can use the unary plus operator as follows:
var x = +prompt('Enter a number');
This will store it as a number in x. Next, we have to print the number in words according to the input value(x). This can be done using switch statement as follows:
var x = +prompt('Enter a number');
switch(x) {
case 1:
console.log('one');
break;
case 2:
console.log('two');
break;
case 3:
console.log('three');
break;
case 4:
console.log('four');
break;
case 5:
console.log('five');
break;
}
Write a program to take a number(using prompt) from 1 to 5 as input and print it in words. If any other number is entered, print “Invalid input”.
This example is similar to the previous example. The only difference is, if we give any number other than 1 to 5 as input, it should print “Invalid input”. For this, we need to use a default case in the switch statement.
var x = +prompt('Enter a number');
switch(x) {
case 1:
console.log('one');
break;
case 2:
console.log('two');
break;
case 3:
console.log('three');
break;
case 4:
console.log('four');
break;
case 5:
console.log('five');
break;
default:
console.log("Invalid Input")
break;
}