CS133JS Beginning Programming: JavaScript

Combining JavaScript Statements

Topics by Week 
1. Intro to JavaScript programming6. Arrays
2. Functions, Operators and Expressions7. Objects and Object Constructors
3. Conditional Statements: if and switch8. Web Page I/O
4. Repetition: while, do while, and for9. Review / Continue Learning
5. Midterm Check-Point10. Final Assessment

Table of Contents

Announcements

Q and A

 

Combined Statements

In JavaScript, as in most programming languages you can combine multiple operations into one statementmeaning you can do multiple things in one line of code. For example, here are a series of JavaScript statements to square a number entered by a user:

We can combine some of the operations and still do exactly the same thing:

 

Combined Statements with Arrays

The possibility for combining operations gets more "interesting" (complicated?) when we are using arrays. For example, we'll make an array of animals and then output all the animals:

We can do exactly the same thing like this:

Here's another example, the Olympic Trials qualifying speed for the women's 100m dash is 11.15 seconds. We'll search an array of times for the runners who qualify:

We can simplify this by directly working with the array elements instead of copying them into variables:

 

Combined Statements with Objects

Objects provide even more opportunities for combining operations. For example we could combine the parallel arrays containing runners and their times into one array that contains runner objects:

We can simply the code in the loop by combining operations to directly operate on objects in array elements:

We can simplify this loop further by using a for-of loop:

Combined Statements with the DOM

Since the objects in the Document Object Model are just JavaScript objects, we can combine multiple statements the operate on the DOM into one statement in the same way we would when working with any other JavaScript objects. Here's an example of setting the text content of an HTML element:

We can combine this all into one statement:

 


Creative Commons License Beginning JavaScript Lecture Notes by Brian Bird, , are licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.