Skip to content

Latest commit

 

History

History
4214 lines (2214 loc) · 253 KB

download (11).md

File metadata and controls

4214 lines (2214 loc) · 253 KB

Skip to main content

Web Fundamentals

1.  User Interface and Git

2.  Advanced CSS and Intro JavaScript

3.  JavaScript Fundamentals

4.  WEB Unit 1 Build

Web Fundamentals

1.  User Interface and Git

2.  Advanced CSS and Intro JavaScript

3.  JavaScript Fundamentals

4.  WEB Unit 1 Build

Intro to JavaScript

JavaScript is the backbone of interactive web pages. This module will tackle basic syntax and logic in JavaScript including variables, math, conditionals, loops, and functions. These building blocks will inform the rest of your career as a web developer.

At the end of this module, you should be able to:

  • understand what Javascript is and explain its use in web development
  • explain global object in JavaScript and be able to use the Math object
  • write control flow using if/else statements
  • write a basic for loop and while loop
  • understand JavaScript functions, why we use them, and be able to write correct function syntax
  • write and call functions using arguments, parameters and the return statement

Pro Tip

If you are going to copy/paste text from an email, be sure to do so without formatting or else: convert the text to “normal” and be sure the text color is “black”

Prepare

Review each preclass resource before class.

Learn

Learn to understand what Javascript is and explain its use in web development

JavaScript is the third of the major building blocks of a web page. Without it, we wouldn’t have the dynamic content and usability we expect from modern websites. We will now learn what it is (and isn’t) and how it is used, not only on the web but in all of its applications.

Overview

What is JavaScript and why do we use it?

JavaScript is a programming language that was first created in 1994 as a way to add functionality and interactivity to a website. If we think back to our analogy of a web page as a house, we will remember that we said that JavaScript is the electricity, plumbing, and gas. It is what makes the web page “run”. JavaScript was originally designed to be used purely on the front end as a way for web developers to add functionality to their web pages, and in its early days, it did just that. Recently, the introduction of the “V8 engine” by Google has improved the speed and functionality of JS. That led to the development and release of exciting new front end JavaScript frameworks and eventually Node.js, a way to run JavaScript on a server (back end). This new development has led to a resurgence of JavaScript. Now, JavaScript is one of the world’s most widely-used programming languages. We can find JavaScript used on the front end, back end, mobile, Internet of Things (IoT), game development, and really anywhere a traditional programming language would be used. Though there are later versions, we will be focusing on and using JavaScript ES6 in this course because it is the most widely applicable.

JavaScript vs Java (and other languages)

Keep in mind, JavaScript is not the same as Java. Although they share similar names (this was, unfortunately, considered a good thing by JavaScript’s early pioneers) that is where the similarities end.

The creators of JavaScript wanted to borrow concepts from other programming languages, such as Scheme, Java, and C. Those of you with backgrounds in other languages may see things that look very familiar, mainly the use of classes and Object-Oriented Programming (OOP) architecture. Keep in mind that JavaScript is not a “true” OOP language and many things you may be familiar with from another language won’t work with JavaScript.

JavaScript is considered a ‘loosely’ typed language, in which types do exist, but they are not enforced. You do not have to declare a type when creating a variable or an array, for instance.

How to ‘run’ JavaScript

For this class, we are going to use a special code sandbox program just like we did with the last lesson (CodePen), called repl.it. This will allow us to write and edit our code and run it right in our browser window to see a real-time read-out.

While this is one way to run your JavaScript, most JavaScript is run from a file with the extension of .js (e.g., fileName.js) and loaded into your browser via the script tag in your HTML.

JavaScript, being the de-facto language of the Internet, can also be run directly within an Internet browser. In fact, you can write all of the JavaScript you want and watch it run in real-time right in your browser by pressing F12 (for Windows), or Cmd+option+J (for Mac) (for Google Chrome). This will open up your console (we will learn more about the console later).

console

Hello World

Hello World is traditionally used to introduce programmers to a new language. The origins of this date back to one of the first computer languages, C, where printing the phrase “hello world” was a major victory.

In JavaScript, printing “Hello, World!” requires just one line of code. Before you move on, try this example to write your first program!

☰

Features

CareersBlogPricingJam

Teams for EducationNEW

Log in

Sign up

We encountered an error. Please tell us what happened by opening up the sidebar and submitting a ticket via the get help button.

legal

terms and services

privacy

subprocessors

DPA

US student DPA

student privacy

repl.it

blog

about

careers

teams for educationNEW

classrooms

pricing

features

IDE

multiplayer

community

teams

hosting

handy links

create a repl

docs

feedback

status page

python packages

import from glitch

social media

facebook

twitter

instagram

discord

languages

Clojure

Haskell

Kotlin

QBasic

Forth

LOLCODE

BrainF

Emoticon

Bloop

Unlambda

CoffeeScript

Scheme

APL

Lua

Ruby

Roy

Python

Node.js

JavaScript

Deno (beta)

Golang

C++

C

C#

F#

HTML, CSS, JS

Rust

Swift

Python (with Turtle)

Basic (beta)

R

Bash

Crystal

Julia

Elixir

Nim

Dart

Reason Node.js

Tcl

Erlang

TypeScript

Pygame

Love2D

Emacs Lisp (Elisp)

PHP Web Server

SQLite

Java

PHP CLI

Pyxel

Raku

Scala (beta)

Nix (beta)

Copyright © 2021 Replit, Inc. All rights reserved.

Variables

At the heart of JavaScript are variables. A variable is a way to store, change and use data in code. To explain this concept, consider your favorite webpage: maybe it’s instagram, maybe an online game. More than likely, there are lots of changing pieces on these pages - instagram has likes and usernames, a video game has character selection, game score, and many more - every one of those changing bits of data is stored in a variable. The variable called score, for example, starts with 0, and changes every time you gather points in the game.

Similarly, you might create a variable called greet and store the value “Hello World” to further simplify your program above to console.log(greet).

The syntax to create a variable is first the keyword, a space, the name we are giving the variable, an equal sign, the value we are assigning the variable, and then a semicolon. (A note for those with previous programming knowledge: JavaScript is a loosely-typed language, which means that a variable can be set, and reset, to any type. We do not need to declare its type when creating the variable.)

There are three keywords used to declare variables -var, let, and const. Each keyword comes with slightly different use cases, mostly based around what happens when you change the value of the variable. Some examples of syntax are below.

var firstName = 'John';
let lastName = 'Smith';
const favoriteFood = 'Taco';

var

var is the ES5 way of declaring a variable. This is a generic variable keyword. Variables created with var can be changed without causing errors. While that sounds like a good thing at first, using var too often might lead to buggy code.

Note in the example below that once you declare the variable, you can change it without having to declare again. This is true with all variable keywords.

var firstName = 'Alice';
firstName = 'Bob';        // <- this would be fine

If var is commonly regarded as bad programming practice, what should we use?

const

A const variable is a variable that cannot be changed later in the code. It’s short for “constant”. In our example above “Bob” could not be changed to “Alice” and would throw an error.

const firstName = 'Alice'
firstName = 'Bob'         // <- this would cause an error

This fixes the bug issue, but we know that sometimes variables do need to change - like, the score of a game. Is there a better solution?

let

Enter let. let is a new ES6 variable keyword. This will assign a variable much like var, but with a little bit different behavior. Most notably, it differs by creating “block level scope”. For our purposes at the moment, let and var function almost exactly the same. When we get to writing functions and loops, we can start to use let to our advantage.

let firstName = 'Alice';
firstName = 'Bob';

To recap:

  • var can be re-assigned and changed.
  • let can be re-assigned but not changed.
  • const cannot be re-assigned nor changed.

Because these three keywords achieve the same thing (storing data in memory and assigning that data a ‘key’ that can be used for access) but behave very differently, there are places in this world for all three. And of course, as with everything, there are some other intricacies to learn about the let const and var keywords that we didn’t cover here today.

Lambda School Rule of Thumb When defining/declaring variables use const until you can’t, then use let.

We highly recommend researching the differences between var, let and const in terms of their scoping rules as well. We’ll cover more on this later on when talking about function vs. block scoping. But for now, I’ll point you towards the Dig Deeper section’s link, How let and const are scoped in JavaScript, for some further understanding here.

Primitive Data Types (String, Number, Boolean)

Primitive data types, also known as basic data types are the simplest data types in JavaScript. They’re sort of like primary colors in that all other data types (which we will learn about in later lessons) are made of these types.

Strings

Strings are blocks of text. They will always be defined with quotation marks around them, either single or double. Any text with quotes around it (even numbers) are strings.

const dog = 'fido';
const string = '2';

Numbers

Numbers are just that, numbers. Numbers do NOT have quotes around them. They can be negative as well. JavaScript does have a limitation on the size of a number (+/- 9007199254740991), but only very rarely will that limitation come up.

const answer = 42;
const negative = -13;

Booleans

Booleans are an important relic from the origins of computer science. It is a dichotomous concept that powers binary code, still the very core of computers. You may have seen binary code in the past (e.g., 0001 0110…). That is Boolean logic. The only booleans in JavaScript are true and false, traditionally written in lowercase letters. These variables are useful when you need to employ some kind of dichotomous (or “yes”/”no”) logic in your code.

const iLoveJavascript = true;
const isThisaString = false;

Note that while Booleans look like strings, the lack of ' around the words indicates that the variable is a boolean and it will work differently under the hood.

Undefined and Null

There are a couple of JavaScript objects that don’t really fit into any type. Those are the values undefined and null. You will get undefined when you are looking for a variable that does not have a value yet. undefined simply means what you are asking for does not exist.

console.log(unkownVar); // undefined

null is an object that we, the developers, set when we want to tell other developers that the item they are looking for exists, but there is no value associated with it. While undefined is set by the JavaScript language, null is set by the developer. If you ever receive null, it means that another developer has set that value to null.

let phoneNumber = '123-456-7890';
phoneNumber = null;

phoneNumber; // null

One last thing to note, neither undefined nor null are strings. They are written just as they are without quotes around them, like a Boolean.

Follow Along

☰

Features

CareersBlogPricingJam

Teams for EducationNEW

Log in

Sign up

We encountered an error. Please tell us what happened by opening up the sidebar and submitting a ticket via the get help button.

legal

terms and services

privacy

subprocessors

DPA

US student DPA

student privacy

repl.it

blog

about

careers

teams for educationNEW

classrooms

pricing

features

IDE

multiplayer

community

teams

hosting

handy links

create a repl

docs

feedback

status page

python packages

import from glitch

social media

facebook

twitter

instagram

discord

languages

Clojure

Haskell

Kotlin

QBasic

Forth

LOLCODE

BrainF

Emoticon

Bloop

Unlambda

CoffeeScript

Scheme

APL

Lua

Ruby

Roy

Python

Node.js

JavaScript

Deno (beta)

Golang

C++

C

C#

F#

HTML, CSS, JS

Rust

Swift

Python (with Turtle)

Basic (beta)

R

Bash

Crystal

Julia

Elixir

Nim

Dart

Reason Node.js

Tcl

Erlang

TypeScript

Pygame

Love2D

Emacs Lisp (Elisp)

PHP Web Server

SQLite

Java

PHP CLI

Pyxel

Raku

Scala (beta)

Nix (beta)

Copyright © 2021 Replit, Inc. All rights reserved.

Declare a variable called ‘name’ with the var keyword. Give it the value of your name. The code below will console.log your variables. Don’t touch this code!

To declare a variable with var we first use the var keyword, followed by the name of our variable, name, and finally the value, Alice

var name = 'Alice';

Declare a variable called ‘food’ with the let keyword. Give it the value of your favorite food. Declaring a variable with let works similarly to var, all we need to do is change the keyword to let. Remember that this will allow for mutability, but will show a warning when you try to change the value.

let food = 'Pizza';

Declare a variable called birthMonth with the const keyword. Give it the value of your birth month (i.e. January or February). Const doesn’t allow for mutability, and much like you can’t change your birth month, you can’t change the value of this variable declared with const.

const birthMonth = 'February';
Challenge

It’s time to check your knowledge with a Variables Challenge. There is a solution link at the bottom of the codepen to check your work.

Dig Deeper

Learn to explain global object in JavaScript and be able to use the Math object

Global objects are pre-written code available to us in JavaScript. They extend the functionality of the language. It is important to learn what these objects are, and how to use them.

Overview

Math Operators

Calculators were the first major computer function. In JavaScript, we have built-in math operators that work exactly as they do on your calculator.

Standard Operators

JavaScript can preform any standard operations - addition (+), subtraction (-), multiplication (*), and division (/) on integers and strings. There are dozens of practical applications of this, mathematical operations being just the beginning.

1 + 1; // returns 2
2 * 2; // returns 4
2 - 2; // returns 0
2 / 2; // returns 1

const num1 = 2
const num2 = 2

num1 + num2 // returns 4

const string1 = 'My name is'
const string2 = 'Bob'

string1 + string2 // returns 'My name is Bob'

%

Something you may not have seen before is the modulo operator (%). This math operator will divide two numbers (integers or floats) and return only the remainder. For example, 10 / 3 is 3 with a remainder of 1, so 10 % 3 (read as ‘10 mod 3’) will return 1 .

21 % 5; // returns 1
21 % 6; // returns 3
21 % 7; // returns 0

Math.pow

We can use the pow method on Math to return a number raised to an exponent. It will take two numbers. The first is the base and the second is the power. For example, Math.pow(5,2) calculates 5 squared, which is 25. See some more examples below:

Math.pow(2,2) // returns 4
Math.pow(3,2) // returns 9
Math.pow(3,3) // returns 27

Math.round, Math.floor, Math.ceil

Math also has methods that will round numbers for us. .round will round a number to the nearest whole number. .floor will always round a number down to the nearest whole number. .ceil will always round up to the nearest whole number.

Math.round(6.5) // returns 7
Math.round(6.45) // returns 6
Math.floor(6.999) // returns 6
Math.ceil(6.0001) // returns 7

Truthiness

In these lessons, we have talked a lot about the Boolean values, true and false. When using an if statement or other statements that expect a Boolean value (such as the !, NOT), if the expression given is not a Boolean value, JavaScript will do something called type coercion and transform whatever it is given into a Boolean value. This is known as “truthy” and “falsey” - yes, seriously. Every data type has some truthiness to it. Here are some examples:

// items that are interpreted as true
true
1
' '
[] // an array, you'll learn more about this later
{} // an object, you'll learn more about this later
function() {}

// items that are interpreted as false
false
0
undefined
null
''

Comparison Operators

JavaScript has a number of comparison and logical operators, (> >= < <= === !==). These operators work just as they would in math: greater than, less than, greater than or equal to, and all the rest. We use these operators to evaluate two expressions. As the computer runs the code, the operator will return either a true (if the statement is true) or a false (if the statement is not true).

1 > 2;     // false
2 < 3;     // true
10 >= 10;  // true
100 <= 1;  // false

The “triple equals” sign ( === ) must not be confused with a single equal sign (which indicates assigning a value to a variable). The triple equal will compare everything about the two items, including type, and return if they are exactly equal or not. (Something to note: there is also a “double equals” ( == ) sign which will compare two items, but it allows type coercion so a string and an integer can be considered equal (1 == '1' // true). Due to this, it is considered bad practice to use the double equal sign. We would like to see you always using the triple equal sign, and you will always see us using it.)

1 === 1;          // true
1 === '1';        // false
'cat' === 'cat';  // true
'cat' === 'Cat';  // false

The last comparison operator we would like to introduce you to has two parts to it.

First is the “NOT” (!). When you see this it will mean that we are asking the opposite of the expression (we will revisit the NOT operator later in this lesson).

With that in mind, we can introduce the “not equals” ( !== ) sign. This will return true if the items are NOT equal to each other, in any way. This, like the triple equal sign, takes type into account.

1 !== 1;          // false
1 !== '1';        // true
'cat' !== 'cat';  // false
'cat' !== 'Cat';  // true

Logical Operators

We can also combine two equality expressions and ask if either of them are true, both of them are true, or neither of them is true. To do this we will use Logical Operators.

&&

The first logical operator we will look at is the “AND” operator. It is written with two ampersands (&&). This will evaluate both expressions and will return true if BOTH expressions are true. If one (or both) of them is false, then this operator will return false. For example, (100 > 10 && 10 === 10) will return true because both statements are true, but (10 === 9 && 10 > 9) will return false because one statement is false.

||

Next up is the “OR” operator. It is written with two vertical bars ( ). This operator will check two expressions and return true if either one is true. It will return false only if BOTH expressions are false. As you’d expect a line where both parts are true would return true. Like so:
(100 > 10 || 10 === 10) //true

Similarly this line where only one expression is accurate, would return true. Like this:

(10 === 9 || 10 > 9) //true

If both expressions are false, like this, then the result will be false.

(10 === 9 || 1 > 9) //false

!

The last logical operator is the “NOT” operator. It is written as a single exclamation mark (!). We saw this operator earlier when determining equality (!==). As before, the NOT operator will return the opposite Boolean value of what is passed to it.

In this first case, since the opposite of false is true, (!false) would return true.

(!false) // true

Similarly since 1 is equal to 1 and this statement is true, !(1===1) would return false thanks to the ! operator.

(!(1 === 1)) // false

Notes About Logical Operators

A couple things to note about logical operators.

  • The expressions are evaluated in order, and the computer will skip any redundant expressions. In an && statement, if the first expression is false, the second expression will not be evaluated because BOTH expressions need to be true. Same for the || statement. If the first expression is true, the second will not be evaluated because there only needs to be one true statement to fulfill the requirements of the operator.

  • Use parentheses. As we saw in the second ! operator example, we used parentheses to evaluate what was inside of the parentheses FIRST, then applied the ! operator. We can wrap ANY expression in parentheses and it will be evaluated before evaluating the expression as a whole.

Follow Along

You may have tried the following riddle on your friend as a kid. Using our knowledge of variables and math we’re going to create a console application to return a person’s birthday starting with just the number 7. The steps we need to take are as follows.

Enter the number 7
Multiply by the month of your birth
Subtract 1
Multiply by 13
Add the day of your birth
Add 3
Multiply by 11
Subtract the month of your birth
Subtract the day of your birth
Divide by 10
Add 11
Divide by 100

☰

Features

CareersBlogPricingJam

Teams for EducationNEW

Log in

Sign up

We encountered an error. Please tell us what happened by opening up the sidebar and submitting a ticket via the get help button.

legal

terms and services

privacy

subprocessors

DPA

US student DPA

student privacy

repl.it

blog

about

careers

teams for educationNEW

classrooms

pricing

features

IDE

multiplayer

community

teams

hosting

handy links

create a repl

docs

feedback

status page

python packages

import from glitch

social media

facebook

twitter

instagram

discord

languages

Clojure

Haskell

Kotlin

QBasic

Forth

LOLCODE

BrainF

Emoticon

Bloop

Unlambda

CoffeeScript

Scheme

APL

Lua

Ruby

Roy

Python

Node.js

JavaScript

Deno (beta)

Golang

C++

C

C#

F#

HTML, CSS, JS

Rust

Swift

Python (with Turtle)

Basic (beta)

R

Bash

Crystal

Julia

Elixir

Nim

Dart

Reason Node.js

Tcl

Erlang

TypeScript

Pygame

Love2D

Emacs Lisp (Elisp)

PHP Web Server

SQLite

Java

PHP CLI

Pyxel

Raku

Scala (beta)

Nix (beta)

Copyright © 2021 Replit, Inc. All rights reserved.

We’ll walk through the example for someone born on February 22. First, we need to create our magical number variable. We’ll use let so that this can be easily changed.

let magicalNumber = 7;

Now, we test the riddle. For every calculation we will need to change the value of magicalNumber and preform the riddle step.

// Multiply by the month of your birth
magicalNumber = magicalNumber * 2
// Subtract 1
magicalNumber = magicalNumber - 1
// Multiply by 13
magicalNumber = magicalNumber * 13
// Add the day of your birth
magicalNumber = magicalNumber + 22
// Add 3
magicalNumber = magicalNumber + 3
// Multiply by 11
magicalNumber = magicalNumber * 11
// Subtract the month of your birth
magicalNumber = magicalNumber - 2
// Subtract the day of your birth
magicalNumber = magicalNumber - 22
// Divide by 10
magicalNumber = magicalNumber / 10
// Add 11
magicalNumber = magicalNumber + 11
// Divide by 100
magicalNumber = magicalNumber / 100

Finally, let’s console.log our magical number and see if it returns 2.22 as expected. If our calculations are correct, this should work for any birthday!

console.log(magicalNumber)

To make this application more useful, you could create a variable called birthMonth and another called birthYear and let the program run on its on.

Challenge

Check your knowledge with a short math challenge.


Learn to write control flow using if/else statements

Overview

Control Flow

Often times, as a computer is reading and executing our code, we want code to run only if something is true or not. For example, add one point to the variable score if the character touches a coin. This is known as control flow or conditional logic. Control flow means that not all code on the screen is executed in order, or at all. We will learn to use some basic control flow today, and will dive deeper into it in our next lesson.

Let’s say you wanted to write a simple script to check whether someone is a legal driver. You could use conditional logic to print a true or false boolean.

☰

Features

CareersBlogPricingJam

Teams for EducationNEW

Log in

Sign up

We encountered an error. Please tell us what happened by opening up the sidebar and submitting a ticket via the get help button.

legal

terms and services

privacy

subprocessors

DPA

US student DPA

student privacy

repl.it

blog

about

careers

teams for educationNEW

classrooms

pricing

features

IDE

multiplayer

community

teams

hosting

handy links

create a repl

docs

feedback

status page

python packages

import from glitch

social media

facebook

twitter

instagram

discord

languages

Clojure

Haskell

Kotlin

QBasic

Forth

LOLCODE

BrainF

Emoticon

Bloop

Unlambda

CoffeeScript

Scheme

APL

Lua

Ruby

Roy

Python

Node.js

JavaScript

Deno (beta)

Golang

C++

C

C#

F#

HTML, CSS, JS

Rust

Swift

Python (with Turtle)

Basic (beta)

R

Bash

Crystal

Julia

Elixir

Nim

Dart

Reason Node.js

Tcl

Erlang

TypeScript

Pygame

Love2D

Emacs Lisp (Elisp)

PHP Web Server

SQLite

Java

PHP CLI

Pyxel

Raku

Scala (beta)

Nix (beta)

Copyright © 2021 Replit, Inc. All rights reserved.

Here we are taking a number (age) and checking to see if the statement is true. The statement 16 > 15 is true, so our code will return true. If it is not, it will skip that chunk of code and return false.

Check For Understanding: Change the value of age above so that the code will return false.

We just learned about the if operator. We can use if to check and see if an expression is true. If it is, JavaScript will run some code. If it is not, JavaScript will skip the code and keep running the program.

if (1 + 1 === 2) {
    console.log('The expression is true!');
}
// since 1 + 1 does equal 2, JavaScript will console.log ("The expression is true!")

if (1 + 1 === 3) {
    console.log('The expression is true!');
}

// since 1 + 1 does NOT equal 2, JavaScript will NOT console.log ("The expression is true!")

To add on to if, we can also use the else and else if statements. These statements must be used only after if has been used. These statements will be evaluated if the initial if returns false. We can think of the else if as another if statement that has been chained (we can have as many else if statements we want). Only one if or else if statement code block will be run. If at any time a statement evaluates to true, that code will be run and the rest will be skipped:

if (1 + 1 === 3) {
    console.log('This will be skipped!'); // since 1 + 1 is NOT 3, this will be skipped
} else if (1 + 1 === 2) {
    console.log('This code will be run.'); // since 1 + 1 is equal to 2, this will be run
} else if (1 - 1 === 0) {
    // 1 - 1 IS 0, however, the previous if statement was already true, so this will be skipped
    console.log('This code will NOT be run.');
}

The else statement will always come at the end of an if-else if chain, and will act as a default. If none of the expressions returned true, the else code block will be run no matter what. If any of the previous if or else if expressions are true, the else statement code block will not be run.

if (1 + 1 === 3) {
    console.log('This will be skipped!'); // since 1 + 1 is NOT 3, this will be skipped
} else if (1 + 1 === 3) {
    console.log('This code will NOT be run'); // since 1 + 1 is NOT 3, this will be skipped
} else {
    console.log('This code will be run'); // since the above were skipped, this will run
}

Why use else-if?

You may be thinking to yourself, “Why not just use a bunch of different if statements? Why use else-if? That is a valid question, and sometimes that is the right approach to take. It is up to you to decide which is the right approach. Remember, when using a block of conditionals, only ONE of the statements will be run, even if there are multiple statements that are true. The same can not be said for multiple if statements; they will run if true regardless of statements before and after. Take this example:

const age = 21;
if(age > 20) {
    console.log('older than 20!');
} else if (age > 15){
    console.log('older than 15!');
} else {
    console.log('younger than 15!');
}

In the above example only older than 20! will be logged even though both the if statement and else if statement were true.

const age = 21;
if(age > 20) {
    console.log('older than 20!');
}
if (age > 15) {
    console.log('older than 15!');
}
if (age <= 15) {
    console.log('younger than 15!');
}

In the above example the first and second if statements would be logged because both of them are true.

As you can see, it will be up to you to decide if you want to have multiple actions based on your data or just one action.

Follow Along

Note: the following example will span several lessons, we suggest forking the repl.it below and saving your work as you go along. As always, you can also code along in the repl.it here.

☰

Features

CareersBlogPricingJam

Teams for EducationNEW

Log in

Sign up

We encountered an error. Please tell us what happened by opening up the sidebar and submitting a ticket via the get help button.

legal

terms and services

privacy

subprocessors

DPA

US student DPA

student privacy

repl.it

blog

about

careers

teams for educationNEW

classrooms

pricing

features

IDE

multiplayer

community

teams

hosting

handy links

create a repl

docs

feedback

status page

python packages

import from glitch

social media

facebook

twitter

instagram

discord

languages

Clojure

Haskell

Kotlin

QBasic

Forth

LOLCODE

BrainF

Emoticon

Bloop

Unlambda

CoffeeScript

Scheme

APL

Lua

Ruby

Roy

Python

Node.js

JavaScript

Deno (beta)

Golang

C++

C

C#

F#

HTML, CSS, JS

Rust

Swift

Python (with Turtle)

Basic (beta)

R

Bash

Crystal

Julia

Elixir

Nim

Dart

Reason Node.js

Tcl

Erlang

TypeScript

Pygame

Love2D

Emacs Lisp (Elisp)

PHP Web Server

SQLite

Java

PHP CLI

Pyxel

Raku

Scala (beta)

Nix (beta)

Copyright © 2021 Replit, Inc. All rights reserved.

Let’s create an algorithm to flip a coin and console.log() “heads” or “tails.” To do this, we’ll generate a random 0 or 1 and write a conditional if statement to return the heads or tails reading.

First lets set up a variable called coinFlip and give it a randomly assigned 0 or 1 value. To do this we need to use two methods of the Math object - Math.round() and Math.random(). Math.random() generates a random number between 0 and 1, and Math.round() rounds that decimal to the nearest whole number.

In the syntax below, Javascript first reads Math.random() and generates a random number, for example, 0.56324. Then it reads Math.round() and applies it to the random number, giving an integer, in this example, a 1.

var coinFlip = Math.round(Math.random());

Add this to your repl.it and console.log() coinFlip a few times to make sure you’re getting a mix of 0s and 1s.

Next up, we’ll add our conditional logic. Since we already have a randomly generated 0 or 1, we can set up an if/else statement where 1 represents "Heads" and 0 represents "Tails".

We’ll write this statement using the syntax we learned above, such that if coinFlip is equal to 1, we will console.log "Heads". Otherwise (else), we can assume coinFlip must be 0 and console.log "Tails".

if (coinFlip === 1){
    console.log("Heads")
} else{
    console.log("Tails")
}

We now have a fully functional coin flipping algorithm! Congratulations. You can view and run the solution code in the pen below. We’ll continue to add to this over the next few objectives.

☰

Features

CareersBlogPricingJam

Teams for EducationNEW

Log in

Sign up

We encountered an error. Please tell us what happened by opening up the sidebar and submitting a ticket via the get help button.

legal

terms and services

privacy

subprocessors

DPA

US student DPA

student privacy

repl.it

blog

about

careers

teams for educationNEW

classrooms

pricing

features

IDE

multiplayer

community

teams

hosting

handy links

create a repl

docs

feedback

status page

python packages

import from glitch

social media

facebook

twitter

instagram

discord

languages

Clojure

Haskell

Kotlin

QBasic

Forth

LOLCODE

BrainF

Emoticon

Bloop

Unlambda

CoffeeScript

Scheme

APL

Lua

Ruby

Roy

Python

Node.js

JavaScript

Deno (beta)

Golang

C++

C

C#

F#

HTML, CSS, JS

Rust

Swift

Python (with Turtle)

Basic (beta)

R

Bash

Crystal

Julia

Elixir

Nim

Dart

Reason Node.js

Tcl

Erlang

TypeScript

Pygame

Love2D

Emacs Lisp (Elisp)

PHP Web Server

SQLite

Java

PHP CLI

Pyxel

Raku

Scala (beta)

Nix (beta)

Copyright © 2021 Replit, Inc. All rights reserved.

````

Challenge

Check your knowledge with the conditionals challenge.


Learn to write a basic for loop and while loop

Loops are fundamental to “DRY” programming and allow you, the developer, to run a chunk of code repeatedly. Understand basic loops and the native for loop implementation in JavaScript.

Overview

Loops

Most software runs on loops, evaluating expressions over and over again until it either returns what we are looking for, or hits a certain number of loops. JavaScript has two looping expressions built into it and today we will look at the first one, the “for” loop.

for Loops

Imagine you wanted to console.log() the phrase hello, world! 5 times. With your current knowledge that would look something like this. This is just for illustration, please, never code like this.

console.log("hello, world!");
console.log("hello, world!");
console.log("hello, world!");
console.log("hello, world!");
console.log("hello, world!");

In general, you should almost never have to copy and paste chunks of code. Not only is it a bad programming practice, it is time consuming, and it leads to errors. Consider, for example, how much work it would be if you wanted to change “world” to someone’s name. So how would you console.log() hello, world! five times? Using for loops! With a for loop, the above example could be reduced to the following.

for (let i = 0; i < 5; i++) {
// | declare a var | conditional expression | increment var|
    console.log("hello, world!");
}

for loops are useful anytime you need to run the same block of code a certain number of times. Imagine you go to the store and want to buy 10 avocados. Instead of scanning each avocado one by one, the cashier will add the cost of one avocado to your total for each avocado you buy. In other words, for each avocado, add cost. This would result in adding cost 10 times.

for loops have a unique syntax, similar to the if statement, but slightly more complex. First, we have the for keyword, followed by parentheses, and then open and close braces. Within the parentheses, we will need three things. First, we must declare a variable (usually i) as a starting point. Then, we will have a conditional expression. The loop will continue happening until this statement is false. Third, we will increment our variable, telling the loop a pattern to follow. Usually, the increment will be i++, meaning increase i by 1 every time the loop runs. All three of these statements are separated by a semicolon.

for (let i = 0      ; i < 10                 ; i++          ) {
//  | declare a var | conditional expression | increment var|
     console.log(i);
}

In this example, we see that we initially set our counter variable (i) to 0. The loop will run and each time it gets to the end, it will increase the counter by one. The for loop will then evaluate the conditional expression. If it is true, it will run again, but if it is false it will stop running. Therefore, the return of the example above would be the following:

☰

Features

CareersBlogPricingJam

Teams for EducationNEW

Log in

Sign up

We encountered an error. Please tell us what happened by opening up the sidebar and submitting a ticket via the get help button.

legal

terms and services

privacy

subprocessors

DPA

US student DPA

student privacy

repl.it

blog

about

careers

teams for educationNEW

classrooms

pricing

features

IDE

multiplayer

community

teams

hosting

handy links

create a repl

docs

feedback

status page

python packages

import from glitch

social media

facebook

twitter

instagram

discord

languages

Clojure

Haskell

Kotlin

QBasic

Forth

LOLCODE

BrainF

Emoticon

Bloop

Unlambda

CoffeeScript

Scheme

APL

Lua

Ruby

Roy

Python

Node.js

JavaScript

Deno (beta)

Golang

C++

C

C#

F#

HTML, CSS, JS

Rust

Swift

Python (with Turtle)

Basic (beta)

R

Bash

Crystal

Julia

Elixir

Nim

Dart

Reason Node.js

Tcl

Erlang

TypeScript

Pygame

Love2D

Emacs Lisp (Elisp)

PHP Web Server

SQLite

Java

PHP CLI

Pyxel

Raku

Scala (beta)

Nix (beta)

Copyright © 2021 Replit, Inc. All rights reserved.

Check For Understanding: Edit the code above to return 1,2,3,4,5,6,7,8,9,10 (each on a new line is fine).

The ++ operator

We saw in the last two examples the ++ operator. This is JavaScript shorthand for “Set the value of the variable to its current value plus one”. There are a few more of these variable math/assignment shorthand expressions. We will visit them in upcoming lessons.

While loops

While loops are similar to for loops in that they make it easy to repeat some action for a desired amount of time. Just like for loops, they will run so long as a condition is met. The key difference here is that you don’t need to declare an incrementing variable when you declare a while loop.

Syntactically, while loops look like this. Note that the example below is what we call an “infinite loop” because the condition will never be false.

while (i === true) {
  console.log("i is true");
}

Most practical example of loops will use some kind of “counter”, an outside variable that will be affected by what’s inside the loop. A more practical example of a while loop, using a counter, might look like:

let count = 1;
while (count < 10) {
    console.log(count);
    count +=2;
}

The return of this loop would be 11 because the loop would add 2 every time it runs, until the value is greater than 10.

Infinite Loops

As mentioned, it is possible to write a loop such that it never ends. This is what we call an “Infinite Loop” and it will break your program. Take for example this loop:

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

Because our conditional expression will ALWAYS be true (i will never be less than 0) this loop will essentially run forever. This will break your program, and may crash your web browser, or computer.

Follow Along

Let’s wrap our heads/tails program in a loop to allow a user to play more than one time.

We’ll start where we left off with the conditional. Its actually fairly simple to add loop functionality. We’re going to wrap this whole chunk of code inside a for loop.

☰

Features

CareersBlogPricingJam

Teams for EducationNEW

Log in

Sign up

We encountered an error. Please tell us what happened by opening up the sidebar and submitting a ticket via the get help button.

legal

terms and services

privacy

subprocessors

DPA

US student DPA

student privacy

repl.it

blog

about

careers

teams for educationNEW

classrooms

pricing

features

IDE

multiplayer

community

teams

hosting

handy links

create a repl

docs

feedback

status page

python packages

import from glitch

social media

facebook

twitter

instagram

discord

languages

Clojure

Haskell

Kotlin

QBasic

Forth

LOLCODE

BrainF

Emoticon

Bloop

Unlambda

CoffeeScript

Scheme

APL

Lua

Ruby

Roy

Python

Node.js

JavaScript

Deno (beta)

Golang

C++

C

C#

F#

HTML, CSS, JS

Rust

Swift

Python (with Turtle)

Basic (beta)

R

Bash

Crystal

Julia

Elixir

Nim

Dart

Reason Node.js

Tcl

Erlang

TypeScript

Pygame

Love2D

Emacs Lisp (Elisp)

PHP Web Server

SQLite

Java

PHP CLI

Pyxel

Raku

Scala (beta)

Nix (beta)

Copyright © 2021 Replit, Inc. All rights reserved.

To do so we’ll utilize the same syntax from above, and for now we’ll tell the loop to run five times. We’ll start by declaring the for keyword, then setting our initial value to 0 (let i = 0). We want the loop to run until i is equal to 5, i < 5, and to add 1 to i every time the loop runs.

for (let i = 0;         i < 5;          i++) {
//   start at 0   | loop until 5   | add one every time

As you might imagine, we can now change the number of coinFlips to preform by changing the conditional expression above, so i < 5 could change to i < 10 and our coin would be flipped 10 times.

Its important to note that the variable needs to go inside of the loop so that it is randomly generated each time the loop runs. Otherwise, coinFlip would be declared outside of the loop and our end result would be 5 heads or 5 tails. Go ahead and try moving the variable around to see what we mean.

With this seemingly simple MVP, you could go on to add a lot of functionality to this program, including user interaction through window.prompt() or by integrating HTML. Again, you can view and run the solution code in the pen below.

☰

Features

CareersBlogPricingJam

Teams for EducationNEW

Log in

Sign up

We encountered an error. Please tell us what happened by opening up the sidebar and submitting a ticket via the get help button.

legal

terms and services

privacy

subprocessors

DPA

US student DPA

student privacy

repl.it

blog

about

careers

teams for educationNEW

classrooms

pricing

features

IDE

multiplayer

community

teams

hosting

handy links

create a repl

docs

feedback

status page

python packages

import from glitch

social media

facebook

twitter

instagram

discord

languages

Clojure

Haskell

Kotlin

QBasic

Forth

LOLCODE

BrainF

Emoticon

Bloop

Unlambda

CoffeeScript

Scheme

APL

Lua

Ruby

Roy

Python

Node.js

JavaScript

Deno (beta)

Golang

C++

C

C#

F#

HTML, CSS, JS

Rust

Swift

Python (with Turtle)

Basic (beta)

R

Bash

Crystal

Julia

Elixir

Nim

Dart

Reason Node.js

Tcl

Erlang

TypeScript

Pygame

Love2D

Emacs Lisp (Elisp)

PHP Web Server

SQLite

Java

PHP CLI

Pyxel

Raku

Scala (beta)

Nix (beta)

Copyright © 2021 Replit, Inc. All rights reserved.

Challenge

Check your knowledge with a short loops challenge


Learn to understand JavaScript functions, why we use them, and be able to write correct function syntax

Overview

Introduction to Functions

Functions allow you, the developer, to repeat sections of code with just a single line. Consider, for a second, you want to “program” a robot to bake you cookies. A practical program, because you’d have cookies all the time! Code, without functions, might include steps like addFlour, addEggs, addChocolateChips, preheatOven, bake. A function could collect these steps into a container called bakeCookies(). Then, running bakeCookies() would produce the same, delicious result as the individual steps.

We mentioned earlier that you never want to copy and paste code, this is not only true when you want to repeat one single action, but also when you want to repeat a whole chunk of actions. In the case of the latter, we use functions.

We can think of functions as small computer programs. Functions allow us to write code that will be used over and over again, keeping our code DRY (“Don’t Repeat Yourself!”).

Before we dive into syntax, study the following example and predict the output.

function myFunc() {
    console.log('this is my function!')
}
myFunc()

If you guessed that the output would be this is my function, congratulations - you are correct! Once you’ve declared a function, like myFunc it can be used over and over again to give the same, predictable result.

☰

Features

CareersBlogPricingJam

Teams for EducationNEW

Log in

Sign up

We encountered an error. Please tell us what happened by opening up the sidebar and submitting a ticket via the get help button.

legal

terms and services

privacy

subprocessors

DPA

US student DPA

student privacy

repl.it

blog

about

careers

teams for educationNEW

classrooms

pricing

features

IDE

multiplayer

community

teams

hosting

handy links

create a repl

docs

feedback

status page

python packages

import from glitch

social media

facebook

twitter

instagram

discord

languages

Clojure

Haskell

Kotlin

QBasic

Forth

LOLCODE

BrainF

Emoticon

Bloop

Unlambda

CoffeeScript

Scheme

APL

Lua

Ruby

Roy

Python

Node.js

JavaScript

Deno (beta)

Golang

C++

C

C#

F#

HTML, CSS, JS

Rust

Swift

Python (with Turtle)

Basic (beta)

R

Bash

Crystal

Julia

Elixir

Nim

Dart

Reason Node.js

Tcl

Erlang

TypeScript

Pygame

Love2D

Emacs Lisp (Elisp)

PHP Web Server

SQLite

Java

PHP CLI

Pyxel

Raku

Scala (beta)

Nix (beta)

Copyright © 2021 Replit, Inc. All rights reserved.

Check For Understanding: Edit the code above to console.log() “Hello, World!” when myFunc() is called.

Function Syntax

Just like we used const, let, and var to declare variables, we use the keyword function to declare functions.

function myFunc() {
// tasks go here
}

The function keyword tells whatever is running your program that what follows is a function and to treat it as such. After that comes the name - we like to give functions names that describe what they do, like logsHello. Then comes an open and a close parentheses, (). And finally, open and close brackets. In between these brackets is where all of our function code will go.

function logsHello() {
    console.log('hello');
}

logsHello();

In this example, we declare a function logsHello and set it up to console.log 'hello'.

In order to run this function, we need to write or invoke its name with the parentheses after it, logsHello(). This is the syntax to run (aka. call) a function. A function always needs parentheses to run.

☰

Features

CareersBlogPricingJam

Teams for EducationNEW

Log in

Sign up

We encountered an error. Please tell us what happened by opening up the sidebar and submitting a ticket via the get help button.

legal

terms and services

privacy

subprocessors

DPA

US student DPA

student privacy

repl.it

blog

about

careers

teams for educationNEW

classrooms

pricing

features

IDE

multiplayer

community

teams

hosting

handy links

create a repl

docs

feedback

status page

python packages

import from glitch

social media

facebook

twitter

instagram

discord

languages

Clojure

Haskell

Kotlin

QBasic

Forth

LOLCODE

BrainF

Emoticon

Bloop

Unlambda

CoffeeScript

Scheme

APL

Lua

Ruby

Roy

Python

Node.js

JavaScript

Deno (beta)

Golang

C++

C

C#

F#

HTML, CSS, JS

Rust

Swift

Python (with Turtle)

Basic (beta)

R

Bash

Crystal

Julia

Elixir

Nim

Dart

Reason Node.js

Tcl

Erlang

TypeScript

Pygame

Love2D

Emacs Lisp (Elisp)

PHP Web Server

SQLite

Java

PHP CLI

Pyxel

Raku

Scala (beta)

Nix (beta)

Copyright © 2021 Replit, Inc. All rights reserved.

Check For Understanding: The function syntax above is correct, but nothing shows up when the program is run! Add a line of code so that the console displays hello.

Function Declaration Hoisting

JavaScript utilizes a two-pass compiler when executing lines of code that we write. This means that anytime we run JavaScript in the browser, the browser will take two passes over our code. The first pass builds up references to all of our code, declaring variables and functions and the like. The second pass applies values to the references that were found, thus actually running the code.

Function declarations are defined in the first pass. The compiler is made aware of the function declaration and adds it to the top of the execution order for your code. This concept of putting a function higher in the execution order for later use is known as hoisting.

What does this mean for you? It means that function declarations can be invoked before they are defined! Let’s take a look at an example:

// This code is valid above the definition!
console.log(add(2,4)) // 6

function add(a,b){
 console.log(a + b);
}

This is odd behavior to developers new to JavaScript. It can be used as a feature or introduce bugs if not understood properly. Be aware that hoisting applies to function declarations and not function expressions or arrow functions.

Function Expressions

Now that we have a better understanding of how basic function syntax works, we can push even further into another type of function, a function expression.

Function expressions have unique differences when compared against function declarations:

  • A variable is used to store the function for later use
  • Anonymous functions are used
  • Function expressions are not hoisted. They can only be invoked after a definition has been placed in the execution stack.

Example of a function expression:

const add = function(a,b){
 console.log(a + b);
}
add(2,4) // 6

Notice the function doesn’t actually have a name. This is what we refer to as an anonymous function. Because we are using a const named add we don’t need to name our function anything. We can simply execute the function when add is referenced by invocation.

Why do this and not use a function declaration? Because we have more control over our code now. We will discuss this in greater detail later on with scope and closure. For now, just know that arrow functions make code more concise.

Arrow Function Expressions

Arrow functions are fancy looking function expressions with a major feature removed, the function keyword. We won’t focus on why this is important right now, Instead, we will start getting used to seeing the syntax of what an arrow function looks like:

// function expression syntax
// const add = function(a,b) {
//  console.log a + b;
// }

// arrow function expression syntax
const add = (a,b) => {
 console.log(a + b);
}
add(2,4) // 6

You will notice that we removed the function keyword in front of our parameters and then added a => token behind the parameters. This is a pretty straightforward conversion!

Syntactically, we didn’t remove much, we lost a few characters in the word function and gained a =>. However, there are many sub-rules for syntax with arrow functions. Those sub-rules can create extremely streamlined syntax. This line of code is a good example.

// streamlined arrow syntax
const add = (a,b) => console.log(a + b);

add(2,4); // 6

Wow, there are a lot of abstractions occurring there! We do not need our {} because they are redundant in the rules of arrow functions. You haven’t seen return statements yet, but they too, are not needed in arrow functions.

It’s fun to see how slim we can get, but a word of caution: stick with the simple conversion first and slowly step into using other syntactical sugar approaches as you progress.

Often, developers will go too far with syntactical sugar, and the code becomes very hard to read. Arrow function expressions are great to use with array methods, for example, but may not be a great choice in a lot of other places.

When Not To Use Arrow Functions

There is a time and place for arrow functions. Here is a list of times you should not be using them:

  • Event handlers (Unless they are inside a class constructor!)
  • Object methods
  • Prototype methods
  • Anytime you need to use arguments Object
Follow Along

Let’s return to our coin flip game to create a function flip() that will run our code with a single line.

☰

Features

CareersBlogPricingJam

Teams for EducationNEW

Log in

Sign up

We encountered an error. Please tell us what happened by opening up the sidebar and submitting a ticket via the get help button.

legal

terms and services

privacy

subprocessors

DPA

US student DPA

student privacy

repl.it

blog

about

careers

teams for educationNEW

classrooms

pricing

features

IDE

multiplayer

community

teams

hosting

handy links

create a repl

docs

feedback

status page

python packages

import from glitch

social media

facebook

twitter

instagram

discord

languages

Clojure

Haskell

Kotlin

QBasic

Forth

LOLCODE

BrainF

Emoticon

Bloop

Unlambda

CoffeeScript

Scheme

APL

Lua

Ruby

Roy

Python

Node.js

JavaScript

Deno (beta)

Golang

C++

C

C#

F#

HTML, CSS, JS

Rust

Swift

Python (with Turtle)

Basic (beta)

R

Bash

Crystal

Julia

Elixir

Nim

Dart

Reason Node.js

Tcl

Erlang

TypeScript

Pygame

Love2D

Emacs Lisp (Elisp)

PHP Web Server

SQLite

Java

PHP CLI

Pyxel

Raku

Scala (beta)

Nix (beta)

Copyright © 2021 Replit, Inc. All rights reserved.

Just like with loops, all we need to do is add another layer of functionality here, so we’ll wrap a function declaration around all the code we already have.

We need to declare the function with the keyword function, then name it with name + (), so here we can write function name() and wrap the whole function in curly brackets ({}) like so.

function flip() {
    // coin flip algorithm goes here
}

When this process is successfully completed, a single line of code (flip()) will run our coin flip game! As usual, view and run solution code below.

☰

Features

CareersBlogPricingJam

Teams for EducationNEW

Log in

Sign up

We encountered an error. Please tell us what happened by opening up the sidebar and submitting a ticket via the get help button.

legal

terms and services

privacy

subprocessors

DPA

US student DPA

student privacy

repl.it

blog

about

careers

teams for educationNEW

classrooms

pricing

features

IDE

multiplayer

community

teams

hosting

handy links

create a repl

docs

feedback

status page

python packages

import from glitch

social media

facebook

twitter

instagram

discord

languages

Clojure

Haskell

Kotlin

QBasic

Forth

LOLCODE

BrainF

Emoticon

Bloop

Unlambda

CoffeeScript

Scheme

APL

Lua

Ruby

Roy

Python

Node.js

JavaScript

Deno (beta)

Golang

C++

C

C#

F#

HTML, CSS, JS

Rust

Swift

Python (with Turtle)

Basic (beta)

R

Bash

Crystal

Julia

Elixir

Nim

Dart

Reason Node.js

Tcl

Erlang

TypeScript

Pygame

Love2D

Emacs Lisp (Elisp)

PHP Web Server

SQLite

Java

PHP CLI

Pyxel

Raku

Scala (beta)

Nix (beta)

Copyright © 2021 Replit, Inc. All rights reserved.

Challenge

Check your knowledge with the functions challenge.

Dig Deeper

Learn to write and call functions using arguments, parameters and the return statement

Parameters and arguments allow us to pass data into functions and use this data within the function. In this objective, we will learn the difference between the two and how to use them.

Overview

Passing Data into Functions

Let’s return to our cookie example. Pretend that you want your robot to bake different types of cookies. Do you need to write a new function for every cookie? Not at all. Instead, you could add a parameter, or variable, called recipe and call bakeCookies('pecan') or bakeCookies('chocolateChunk').

Parameters are how functions accept changing data. Consider the example below.

function add(num1, num2) {
  return (num1 + num2);
}

add(2,2) // returns 4
add(4,5) // returns 9

We can declare variables called parameters (num1 and num2 in the example above) that represent data we will use when calling the function. This is similar to algebra. X + Y = Z would be a pretty meaningless equation, but once we substitute real numbers for X and Y, we can easily solve for Z. Here, X and Y are analogous to parameters, and the real numbers to arguments.

We’ll dive into details about both parameters and arguments in this section, but the differences can be summarized as follows.

  • Function parameters are the names listed in the function’s definition.
  • Function arguments are the real values passed to the function.
  • Parameters are initialized to the values of the arguments supplied.

Parameters

As illustrated above, a function parameter will represent the data we pass into a function, for use in the function. Essentially when we write a function we assign the data variable names, even without knowing what the data will be. We set these variables inside of the parentheses when we write the function. There is no limit to the amount of parameters we can include in a function, but each variable name must be separated by a comma. We can then use these variables within our function just as we would any other variable.

function myFunc( parameter1, parameter2) {
    // We can use parameter1 and parameter2 in this function just like a variable
}

Arguments

Once we have our parameters set up in our function, we can now pass data into the function. In order to do this, we will put each piece of data inside the the parentheses we write when we call the function. We call these pieces of data arguments. arguments can be ANY data type (string, number, Boolean, object, array, even other functions!). Unlike other languages, JavaScript does not require us to set the data type when we write the function, although you should make an effort to understand what type of data will be coming into the function (and if you are using pre-built functions, you should know what data type that function expects).

To use an argument, just put the data in the function call parentheses like so:

function logsName(name){
    console.log(name);
}

logsName('Dan'); // returns Dan
logsName('Diandra'); // returns Diandra

If you have more than one parameter, you will use more than one argument:

function logsSchool( School, descriptor ){
    console.log(`${School} ${descriptor}`);
}

logsSchool('Lambda', 'is Awesome!'); // logs Lambda is Awesome!

Arguments will always line up with parameters in order, so the first argument will be the first parameter, and so on.

If an argument is not given for a parameter, the parameter will be equal to undefined.

☰

Features

CareersBlogPricingJam

Teams for EducationNEW

Log in

Sign up

We encountered an error. Please tell us what happened by opening up the sidebar and submitting a ticket via the get help button.

legal

terms and services

privacy

subprocessors

DPA

US student DPA

student privacy

repl.it

blog

about

careers

teams for educationNEW

classrooms

pricing

features

IDE

multiplayer

community

teams

hosting

handy links

create a repl

docs

feedback

status page

python packages

import from glitch

social media

facebook

twitter

instagram

discord

languages

Clojure

Haskell

Kotlin

QBasic

Forth

LOLCODE

BrainF

Emoticon

Bloop

Unlambda

CoffeeScript

Scheme

APL

Lua

Ruby

Roy

Python

Node.js

JavaScript

Deno (beta)

Golang

C++

C

C#

F#

HTML, CSS, JS

Rust

Swift

Python (with Turtle)

Basic (beta)

R

Bash

Crystal

Julia

Elixir

Nim

Dart

Reason Node.js

Tcl

Erlang

TypeScript

Pygame

Love2D

Emacs Lisp (Elisp)

PHP Web Server

SQLite

Java

PHP CLI

Pyxel

Raku

Scala (beta)

Nix (beta)

Copyright © 2021 Replit, Inc. All rights reserved.

Check For Understanding: Call logsPerson to return a greeting with your name, city, and favorite color without changing the function itself.

The return Statement

We will not always want to console.log() everything that comes out of a function. Most likely we will want to return something for use in other operations. The only way for us to use data that is local to a function is with the keyword return. return, essentially, lets data escape a function. Nothing other than what is returned can be accessed outside of the function. return is always the last thing in a function because when the function hits a return statement, the function immediately stops everything else that it is doing.

We can also assign the value of a return statement to another variable, and we will now have access to the data returned from the function.

function addTwoNumbers(num1, num2) {
   const sum = num1 + num2;
   return sum;
   console.log('This will never be reached');
}

const newSum = addTwoNumbers( 1, 2 );
console.log(addTwoNumbers(1,2)); //returns 3
console.log(sum); // returns undefined - sum exists only inside the function
console.log(newSum); // returns 3 - value is held in newSum
  • Note: We will never be able to have access to the actual variable created in the function. We will only have access to the data that variable was assigned to.

☰

Features

CareersBlogPricingJam

Teams for EducationNEW

Log in

Sign up

We encountered an error. Please tell us what happened by opening up the sidebar and submitting a ticket via the get help button.

legal

terms and services

privacy

subprocessors

DPA

US student DPA

student privacy

repl.it

blog

about

careers

teams for educationNEW

classrooms

pricing

features

IDE

multiplayer

community

teams

hosting

handy links

create a repl

docs

feedback

status page

python packages

import from glitch

social media

facebook

twitter

instagram

discord

languages

Clojure

Haskell

Kotlin

QBasic

Forth

LOLCODE

BrainF

Emoticon

Bloop

Unlambda

CoffeeScript

Scheme

APL

Lua

Ruby

Roy

Python

Node.js

JavaScript

Deno (beta)

Golang

C++

C

C#

F#

HTML, CSS, JS

Rust

Swift

Python (with Turtle)

Basic (beta)

R

Bash

Crystal

Julia

Elixir

Nim

Dart

Reason Node.js

Tcl

Erlang

TypeScript

Pygame

Love2D

Emacs Lisp (Elisp)

PHP Web Server

SQLite

Java

PHP CLI

Pyxel

Raku

Scala (beta)

Nix (beta)

Copyright © 2021 Replit, Inc. All rights reserved.

Check For Understanding: Declare a variable to save Alice’s lottoTicket autoresponse and another to save Bob’s lottoTicket autoresponse.

Follow Along

When we left our coin flip game, it flipped the coin 5 times, according to the conditional expression in our for loop.

☰

Features

CareersBlogPricingJam

Teams for EducationNEW

Log in

Sign up

We encountered an error. Please tell us what happened by opening up the sidebar and submitting a ticket via the get help button.

legal

terms and services

privacy

subprocessors

DPA

US student DPA

student privacy

repl.it

blog

about

careers

teams for educationNEW

classrooms

pricing

features

IDE

multiplayer

community

teams

hosting

handy links

create a repl

docs

feedback

status page

python packages

import from glitch

social media

facebook

twitter

instagram

discord

languages

Clojure

Haskell

Kotlin

QBasic

Forth

LOLCODE

BrainF

Emoticon

Bloop

Unlambda

CoffeeScript

Scheme

APL

Lua

Ruby

Roy

Python

Node.js

JavaScript

Deno (beta)

Golang

C++

C

C#

F#

HTML, CSS, JS

Rust

Swift

Python (with Turtle)

Basic (beta)

R

Bash

Crystal

Julia

Elixir

Nim

Dart

Reason Node.js

Tcl

Erlang

TypeScript

Pygame

Love2D

Emacs Lisp (Elisp)

PHP Web Server

SQLite

Java

PHP CLI

Pyxel

Raku

Scala (beta)

Nix (beta)

Copyright © 2021 Replit, Inc. All rights reserved.

To allow our users to flip the coin a variable number of times we can use a parameter, repeat.

function flip(repeat){
    // add parameter
}

We will reference repeat into our conditional expression which will cause the loop to run a variable number of times.

function flip(repeat) {
  for (let i = 0; i < repeat; i++) {
      // use parameter as conditional expression
  }
}

When we run the function, we’ll substitute the variable repeat for a number. For example, substituting repeat for 10, would flip the coin 10 times.

flip(10); // <- will flip coin 10 times

Our final product will look something like this. Play around with the repeat argument here until you can clearly explain how the argument changes the functions output.

☰

Features

CareersBlogPricingJam

Teams for EducationNEW

Log in

Sign up

We encountered an error. Please tell us what happened by opening up the sidebar and submitting a ticket via the get help button.

legal

terms and services

privacy

subprocessors

DPA

US student DPA

student privacy

repl.it

blog

about

careers

teams for educationNEW

classrooms

pricing

features

IDE

multiplayer

community

teams

hosting

handy links

create a repl

docs

feedback

status page

python packages

import from glitch

social media

facebook

twitter

instagram

discord

languages

Clojure

Haskell

Kotlin

QBasic

Forth

LOLCODE

BrainF

Emoticon

Bloop

Unlambda

CoffeeScript

Scheme

APL

Lua

Ruby

Roy

Python

Node.js

JavaScript

Deno (beta)

Golang

C++

C

C#

F#

HTML, CSS, JS

Rust

Swift

Python (with Turtle)

Basic (beta)

R

Bash

Crystal

Julia

Elixir

Nim

Dart

Reason Node.js

Tcl

Erlang

TypeScript

Pygame

Love2D

Emacs Lisp (Elisp)

PHP Web Server

SQLite

Java

PHP CLI

Pyxel

Raku

Scala (beta)

Nix (beta)

Copyright © 2021 Replit, Inc. All rights reserved.

Challenge

Check your knowledge with the arguments and parameters challenge.


Project

Review

Class Recordings

You can use class recordings to help you master the material.

Demonstrate Mastery

To demonstrate mastery of this module, you need to complete and pass a code review on each of the following: