Giter VIP home page Giter VIP logo

conditionals_loops_functions's Introduction

JS Conditionals, Loops, Functions

Learning Goals

  • Use comparisons, if/else, and conditionals
  • Use for loops and while loops
  • Use functions, parameters, and return values

Conditionals

Basics

You can compare any two values with the following operators:

  • >, greater than
  • >=, greater than or equal to
  • <, less than
  • >=, less than or equal to
  • ===, equal to
  • !==, not equal to

We use conditionals to control which lines of code run. Our main tool is the if statement:

if (1 + 1 === 2) {
  console.log('Math still works!')
} else {
  console.log('We are in some serious trouble now')
}

The code inside the first set of curlies will only run if the conditional in the parentheses evaluates to true. The code inside the second set of curlies will only run if the conditional evaluates to false.

else if

We can also use additional ifs to create multiple possible outcomes:

const grade = 85
if (grade >= 90) {
  console.log('Grade is an A')
} else if (grade >= 80) {
  console.log('Grade is a B')
} else if (grade >= 70) {
  console.log('Grade is a C')
} else {
  console.log('Time for more practice')
}

The first conditional will not fire because the grade is too low. The second conditional will fire. The third and fourth ones will not even be attempted, because we had success with the second one.

Conjunctions

You should also know about && and ||. These are used to join together two conditionals like so:

'pete' === 'pete' && 5 < 4
'pete' === 'pete' || 5 < 4
'pete' === 'henry' && 3 === 10
'pete' === 'henry' || 3 === 10

Will each of these lines be true or false?

Try the exercises in conditionals.js!

Loops

There are two kinds of loops we will work with: for and while. The for loop looks like this:

for loop

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

Let's take a minute to understand how javascript reads this.

while loop

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

What are some differences between these formats? What are some similarities?

One very important trick is to loop through an array by using the array's .length property:

const greetings = ['hi', 'hello', 'sup']
for (let i = 0; i < greetings.length; i++) {
  console.log(greetings[i])
}

Another important trick is looping through objects:

const pets = {
  violet: 'Pitbull',
  hercules: 'Pinscher'
}

for (let dogName in pets) {
  console.log(`${dogName} is a wonderful ${pets[dogName]}`)
}

Note that pets.dogName is not the same as pets[dogName]! What's the difference?

Try the exercises in loops.js!

Functions

Basics

A function lets you pre-package code to be used later.

function greet() {
  console.log('good day to you!')
}

This will not print right away, but it will allow you to print later, as many times as you want. (One of the main reasons we wrap our code in functions is so we can reuse it multiple times later.)

To use this function, we have to invoke it like this:

greet()

What happens if you take off the closing parentheses?

Parameters

Sometimes pre-packaged instructions require additional information to be run. If I told you "Go on a road trip", you might ask... where to? If I told you "Go paint a picture", you might ask... of what? You need an additional parameter to complete the instructions. We can set our functions up so that they use an additional piece of information too:

function greetSomeone(name) {
  console.log(`good day to you, ${name}!`)
}

The addition of name in the round parentheses indicates that this function needs to be passed a name in order to run. We invoke it like this:

greetSomeone('Henry')

When we invoke it like this, 'Henry' is called the argument. What happens if you omit the argument?

Let's take a minute to follow how the information flows when we invoke with an argument.

Note that a function can take any number of arguments! You separate them with a comma in the function declaration, and you invoke the function with arguments separated by commas:

function greetMany(name1, name2) {
  console.log(`good day to you both, ${name1} and ${name2}!`)
}
greetMany('Henry', 'Weston')

Scope

What happens if you run this code?

const outsideVar = 'I am outside!'
function scopeExperimentation() {
  const insideVar = 'I am inside!'

  console.log(outsideVar)
  console.log(insideVar)
}

scopeExperimentation()

console.log(outsideVar)
console.log(insideVar)

We have just discovered scope! The variable we declared outside the function are visible both inside the function and outside it. But the variable we declared inside the function is only visible inside the function. The same is true for if statements and loops.

return

Consider this code:

function addSalesTax(cost) {
  const tax = cost * 0.07
  const final = cost + tax
}

const total = addSalesTax(25.50)

What is the value of our total variable? The problem is that variables created inside the function aren't visible to the outside world. If we want to make information available to the outside world, we have to use return.

conditionals_loops_functions's People

Contributors

pmacaluso3 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.