NUS Hackers Wiki
NUS Hackers Wiki
  • NUS Hackers Wiki
  • Hackerschool
    • Virtual Machines and Linux
    • Beginners' Guide to the Terminal
      • Introduction to the Terminal
      • Modern Shell Tools
      • Shell Scripting
      • Real World Scripting
      • Resources
    • Self-Hosting: Three Easy Pieces
      • 1. Setting up your server
      • 2. Running Services
      • 3. Monitoring your server
    • Vim
    • Introduction to Zig
      • Language Basics
      • Error Handling
      • Memory Management
      • Working with C
      • Exploring comptime
    • CI/CD with Github Actions
      • Background
      • Basics of Github Actions
        • Target workflow
        • Running unit tests
        • Linting code
        • Deploying to Github Pages
      • Advanced use cases
        • Pollers
        • Github script
        • Executing third-party scripts
        • Reusable workflows
      • Cookbook
    • Lightning Git
      • Git Concepts
      • Getting Started with Git
      • Making your first commit
      • Branching
      • Merge Conflicts
      • Integrating remote repositories
      • Collaborative Workflows
      • Commit Manipulation and Reflog
      • Interactive rebasing
      • filter-repo
  • Orbital
    • JavaScript
      • Browser Developer Tools
      • Getting Started
      • Datatypes
      • Operators and Operations
      • Loops and Conditions
      • Functions
      • Strings
      • Arrays
      • HTML
        • Getting Started
        • Tag Attributes
        • HTML Forms
        • Browser Inspector
      • CSS
        • Selectors
        • Colors in CSS
        • Measurements in CSS
        • The Box Model
        • Adding Styles - Part 1
        • Adding Styles - Part 2
      • Working with the DOM
        • Querying the DOM - Selectors
        • Querying the DOM - Element Attributes
        • Querying the DOM - Element Styles
        • Events with JS and HTML
        • Exercise: Click Counter
        • Editing the DOM
        • Fetch Requests
        • Exercise: The NUSMods API
    • React
      • Setup
      • State
    • React Native
      • Setup
      • Intro to JSX
      • Basic Syntax
      • Handling UI
      • Props
      • State Management
    • Git
      • Setup
      • Command Glossary
      • Fundamental Concepts
        • Getting Started
        • Integrating Remote Repositories
        • Branching
        • Merge Conflicts
      • Collaborative Workflows
        • Fork and PR Workflow
        • Branch and PR Workflow
      • Advanced Concepts
        • Ignoring Files
        • Commit Message Conventions
        • Github Collaborators
        • CI/CD with Github Actions
        • Advanced Git Commands
      • FAQ
    • Telegram Bot
      • Creating a TeleBot
      • API Calls
      • Telebot Basics
      • Integrating API's
    • Relational Database
      • Database Overview
      • Database Design
      • Entity Relationship Diagram
      • SQL Basics & PostgreSQL
    • TypeScript
      • Types and Interfaces
      • Utility Types
      • Typing Component Props, Events, and Hooks
      • Why You Should Avoid Using any (and What to Do Instead)
      • TypeScript Tricks You’ll Use All the Time in React
Powered by GitBook
On this page
  • Conditionals
  • Ternary operation
  • Loops
  • Next steps
Edit on GitHub
Export as PDF
  1. Orbital
  2. JavaScript

Loops and Conditions

Now that we have understood the basic datatypes and operations of JavaScript, we can start learning about other constructs. This section will cover loops and conditions.

To clear the code in the console, type and enter clear(); or hit ctrl + L. This will still keep any variables you declared earlier.

To write multiple lines without executing them one at a time, hit ctrl + enter (or cmd + return for Mac) after every line instead of just enter. This will be useful for the this and the next few sections.

Conditionals

Conditionals are a set of statements that execute different blocks of code based on the evaluation of one or more boolean expressions. In simpler words, if something is true then one thing happens otherwise something else happens.

The syntax for conditional statements in JavaScript is as follows:

if (booleanExpression) {
    // do thing 1
} else if (otherBooleanExpression) {
    // do thing 2
} else {
    // do something else
}

Example:

let num = prompt("Enter a number"); // recall that this allows the user to input a value
if (num === null) { // prompt() returns null if the user gives no input
    alert("You did not enter a number");
} else if (num % 2 === 0) {
    alert("The number you entered was even");
} else {
    alert("The number you entered was odd");
}

Ternary operation

This is an operation that operates on 3 operands, specifically to allow the evaluation of a conditional statement in a single line. Like any other operation, ternary conditions can be nested. The syntax is as follows:

predicate ? returnIfTrue : returnIfFalse;

Example:

// assume num is guaranteed to be a number
num % 2 === 0 ? "Even" : "Odd"; // if num is even then "Even" is returned, else "Odd" is returned

Loops

A loop is a block of code that gets executed repeatedly until an end condition is satisfied. There are two types of loops in JavaScript, the for loop and the while loop. The syntax for each is as follows:

for (counter; limit; step) {
    // do something
}

while (condition) {
    // do something
}

An example of a for loop is as follows:

for (let i = 0; i < 11; i++) {
    console.log(i);
}

The loop above will print out numbers from 0 to 10 one by one. As you can see, first the counter is declared (let i = 0), then the limit is defined (loop keeps executing as long as i < 11), and then the step is defined (i is incremented by 1 each time; i++). The eventual output will look like this:

An while loop that does the same thing as the for loop above would be as below:

let i = 0;
while (i < 11) {
    console.log(i);
    i++;
}

Note that here, the counter variable declaration needs to be done outside the loop, and the step is defined inside the loop. This is because the while loop only has a boolean expression in its keyword call. Omitting to declare the counter variable will lead to a ReferenceError: i is not defined. On the other hand, omitting the step will cause an infinite loop, since the value of i will never change and is always less than 11.

In a for loop, the step can be of any size and can involve valid operation:

for (let k = 1024; k > 1; k /= 2) {
    console.log(k);
}

The above code prints out numbers backwards from 1024, each time dividing k by 2, as long as k is greater than 1.

The counter variable can also be of any type, and you can declare multiple counter variables:

for (let i = 0, j = 15; i < 5; i++, j -= 3) {
    console.log(i, j); // prints the values of i and j separated by a space
}

Here i increases by 1 each time from 0 to 4 (stopping at 5) while j decreases by 3 each time starting from 15 until the loop ends.

A loop involving strings:

let str = "eowjpfi45ofr;kl143";
let i = 0;
while (i < str.length) {
    console.log(str[i]);
    i += 2;
}

This loop prints every 3rd character of str, starting from the 1st one. The same result can be achieved with a for loop:

for (let i = 0; i < str.length; i += 2) {
    console.log(str[i]);
}

Similar results can be achieved with an array.

Next steps

In the next section, we'll look at functions, their types, and how to declare and use them.

PreviousOperators and OperationsNextFunctions

Last updated 12 months ago

Firefox's browser console is able to catch errors and pre-empt the results of executing a block of code before you actually run it. In the screenshot above, you can see ReferenceError: i is not defined in grey text, because the program has not yet run but the console knows what the result is going to be. This tells me as the programmer to look for the problem and fix it before running the code.