image

This is part 2 in a 3-part JavaScript Crash Course to help you prepare for the 21-Day Coding Challenge. The challenge is back on November 22, 2021, and it's your opportunity to learn basic JavaScript in just 15-30 minutes a day in a fun, free environment while racking up your points to win fabulous prizes. Are you up to the challenge? Register now.

Focusing on FOCAL

The challenges in the 21 Day Coding Challenge will focus on something we at Lighthouse Labs like to call FOCAL. That stands for:

  • Functions
  • Objects
  • Conditionals
  • Arrays
  • Loops.

Functions

We might find ourselves wanting to use a piece of code over and over again. To prevent having to rewrite this code in several different places, we can use a function. A function is a named block of code that performs a particular task. And in JavaScript, functions are everywhere.

image

Most of the challenges in the 21 Day Coding challenge will ask that you write a function that takes in something (a parameter) and returns something else.

Passing parameters

    function sayHello (name) {
        console.log("Hello " + name )
    }

    sayHello("Nima")
    // would log "Hello Nima" to the console

Returning values from functions

     function getName() {
        return "Sherman"
     }

     console.log(getName())
     // would log "Sherman" to the console

Practice

  1. Declare a function named greet that logs “Good Morning” to the console when it is called.
  2. Declare a function named greet that takes a person’s name as a parameter, and then logs to the console a “Good morning” message for this person. For example, if the input to the function is ‘Maggie’, the function should log Good morning, Maggie to the console.
  3. Declare a function named getWeatherAdvice() that takes a parameter specifying the weather, and logs to the console advice about you should wear. For example, if the input is ‘raining’, it should tell you to bring an umbrella. If the input to the function is ‘sunny’, it should tell you to wear sunglasses.

Objects

JavaScript objects can contain many values, much like arrays, but organized as key:value pairs. They are a really useful way to store data, and an essential part of understanding JavaScript.

We’ll likely come across Objects in some of the later challenges, where we’ll need to know a few things about them like:

The basic structure of an object:

     let obj = {
        key : "value"
     }

    let person = {
        firstName: "Brandi",
        lastName: "Vieira",
        location: "Whistler"
     };

Accessing a value in an object:

     console.log(person.firstName) // "Brandi"
     console.log(person.lastName) // "Vieira"

Updating a value in an object:

     console.log(person.firstName)
     // "Brandi"

     person.firstName = "Amy"
     console.log(person.firstName)
     // "Amy"

Move on to part 3 of our prep series, or rewind to part 1.