Computer Science
Javascript If Statement
The JavaScript if statement is a conditional statement that executes a block of code if a specified condition is true. It allows for the creation of decision-making processes in a program, enabling different actions to be taken based on different conditions. This fundamental programming construct is essential for controlling the flow of a program based on specific criteria.
Written by Perlego with AI-assistance
Related key terms
1 of 5
4 Key excerpts on "Javascript If Statement"
- eBook - ePub
Processing
An Introduction to Programming
- Jeffrey L. Nyhoff, Larry R. Nyhoff(Authors)
- 2017(Publication Date)
- Chapman and Hall/CRC(Publisher)
do not perform the action of adding salt.Such a conditional action is sometimes represented as a flowchart :Similarly, a computer program may include conditional statements. Such statements are performed selectively , only if a certain condition is true.The Basic if StatementMost programming languages provide a very powerful feature for conditional action: the if statement . In Processing, the basic if statement is typically written in the formif ( condition ){ Statement(s) to perform if the condition is true }Unlike the other statements we have written so far, the if statement is usually written as more than one line of code, and yet it is still considered to be a single statement.Let’s take a closer look at the items of information that we need to supply for the general form of the if statement. First, an if statement needs a test condition .if (condition )This test condition is usually a comparison that will always turn out to be either true or false . This kind of true-or-false comparison is also known as a Boolean expression.* In Processing, the basic operators for comparison, known as the relational operators , are the following:> Greater than< Less than>= Greater than or equal to<= Less than or equal to!= Not equal to== Equal toSecond, we need to specify one or more statements that will be performed if —and only if—the condition is true . We will enclose any such statement(s) in a pair of curly braces, creating what is known as a block of statements.if (condition ){ Statement(s) to perform if the condition is true }Basic if Statement Example: Rolling a Die GameLet’s return to the die-rolling Roll program from Chapter 3 - eBook - ePub
- Jeremy McPeak(Author)
- 2015(Publication Date)
- Wrox(Publisher)
true , you execute a particular section of code.Look at another example. Recall from Chapter 1 the natural English instructions used to demonstrate how code flows. One of these instructions for making a cup of coffee is:- Has the kettle boiled? If so, then pour water into cup; otherwise, continue to wait.
This is an example of making a decision. The condition in this instruction is “Has the kettle boiled?” It has a true or false answer. If the answer is true , you pour the water into the cup. If it isn’t true , you continue to wait.In JavaScript, you can change the flow of the code’s execution depending on whether a condition is true or false , using an if statement or a switch statement. You look at these shortly, but first we need to introduce some new operators that are essential for the definition of conditions—comparison operators.Comparison Operators
In Chapter 2 you saw how mathematical functions, such as addition and division, were represented by symbols, such as plus (+ ) and forward slash (/ ), called operators. You also saw that if you want to give a variable a value, you can assign to it a value or the result of a calculation using the equals sign (= ), termed the assignment operator.Decision making also has its own operators, which enable you to test conditions. Comparison operators, just like the mathematical operators you saw in the preceding chapter, have a left-hand side (LHS) and a right-hand side (RHS), and the comparison is made between the two. The technical terms for these are the left operand and the right operand. For example, the less-than operator, with the symbol < , is a comparison operator. You could write 23 < 45 , which translates as “Is 23 less than 45?” Here, the answer would be true (see Figure 3.1 - eBook - PDF
- Cay S. Horstmann(Author)
- 2014(Publication Date)
- Wiley(Publisher)
4 C H A P T E R 155 DECISIONS To implement decisions using if statements To compare integers, floating-point numbers, and strings To write statements using the Boolean data type To develop strategies for testing your programs To validate user input C H A P T E R G O A L S C H A P T E R C O N T E N T S 4.1 THE IF STATEMENT 156 Syntax 4.1: if Statement 158 Programming Tip 4.1: Brace Layout 160 Programming Tip 4.2: Always Use Braces 160 Common Error 4.1: A Semicolon After the if Condition 160 Programming Tip 4.3: Tabs 161 Special Topic 4.1: The Conditional Operator 161 Programming Tip 4.4: Avoid Duplication in Branches 162 4.2 COMPARING VALUES 162 Syntax 4.2: Comparisons 163 Common Error 4.2: Using == to Compare Strings 168 How To 4.1: Implementing an if Statement 169 Worked Example 4.1: Extracting the Middle Computing & Society 4.1: Denver’s Luggage Handling System 171 4.3 MULTIPLE ALTERNATIVES 172 Special Topic 4.2: The switch Statement 175 4.4 NESTED BRANCHES 176 Programming Tip 4.5: Hand-Tracing 179 Common Error 4.3: The Dangling else Problem 180 Special Topic 4.3: Block Scope 181 Special Topic 4.4: Enumeration Types 182 4.5 PROBLEM SOLVING: FLOWCHARTS 183 4.6 PROBLEM SOLVING: SELECTING TEST CASES 186 Programming Tip 4.6: Make a Schedule and Make Time for Unexpected Problems 188 Special Topic 4.5: Logging 188 4.7 BOOLEAN VARIABLES AND OPERATORS 189 Common Error 4.4: Combining Multiple Relational Operators 192 Common Error 4.5: Confusing && and || Conditions 192 Special Topic 4.6: Short-Circuit Evaluation of Boolean Operators 193 Special Topic 4.7: De Morgan’s Law 193 4.8 APPLICATION: INPUT VALIDATION 194 Computing & Society 4.2: Artificial Intelligence 197 156 One of the essential features of computer programs is their ability to make decisions. Like a train that changes tracks depending on how the switches are set, a program can take different actions depending on inputs and other circumstances. - eBook - ePub
Anyone Can Code
The Art and Science of Logical Creativity
- Ali Arya(Author)
- 2020(Publication Date)
- Chapman and Hall/CRC(Publisher)
Key Point: Golden Rule of Programming #3: Programs run sequentially and linearly, by default. Various control flow mechanisms can alter this, including functions, selection, and iteration.4.2 Selection
In Chapter 2 , I explained the basic idea of selection and conditional statements. Exhibit 4.2 shows the basic design of a selection construct. A selection has at least one condition (c1 in Exhibit 4.2 ) and a block of code (at least one line) associated with it. Other conditions are optional and that includes a default condition when none of the other conditions are true. The selection provides multiple paths (one for each condition), which all merge at the end, and the program continues normally after that.4.2.1 If/Else
Sample Code #2-j demonstrates possible forms of selection using the keywords if and else . The program receives a student grade (0–100) and detects if the student has failed (less than 50), should receive a medal (greater than 90), or just passes the course. Line 13 is executed regardless of the conditions. The sample code also illustrates the use of a common Javascript function, alert(), that displays a message on the screen.Sample Code #2-j 1. <p id="demo">?</p> 2. 3. <script> 4. function Grade() 5. { 6. var grade = data.value; 7. if(grade >= 90) 8. demo.innerHTML = "Congrats! You get a medal."; 9. else if(grade < 50) 10. demo.innerHTML = "Sorry. You failed."; 11. else 12. demo.innerHTML = "Good. You passed." 13. alert("Bye"); 14. } 15. 16. </script> 17. <input id="data"> 18. <button onclick="Grade();">Grade</button>We will discuss functions in the next chapter. For now, we just need to know that they are defined by the following parts:- A keyword specifying the type
- In C/C++, we specify the data type. All examples in this chapter use void, and we discuss all the options in the next chapter.
- In Python and Javascript, functions and variables don’t have explicitly defined types. Defining functions is by using the keyword function in Javascript and def in Python.
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.



