Git Product home page Git Product logo

javascript-arithmetic-lab's Introduction

JavaScript Arithmetic Lab

Objectives

  • Practice doing math with JavaScript
  • Practice writing functions that do things with numbers
  • Practice parsing strings as numbers

Introduction

In this lab, we're going to practice writing functions and manipulating numbers in JavaScript. First, though, we need to go over some basic math. In this lab, we're going to learn about various arithmetic operators. What's an operator, you say? It's a symbol that operates on one or more (usually two) objects — + is a good example. The + operator says "add what's to the left of + and what's to the right of + together."

As you read through this lesson, you're going to be adding your solutions to index.js. You'll write a total of eight functions; use the results of running learn test in your IDE to guide you towards the right function names and functionality.

Basic Math

The most fundamental math operations work as one might expect in JavaScript: + adds two numbers; - subtracts one number from another; * multiplies two numbers; and / divides one number by another. For example (as usual, follow along in console!)

1 + 80 // 81
60 - 40 // 20
2 * 3.4 // 6.8 (there's that floating-point arithmetic again...)
5.0 / 2.5 // 2

At this point, we can fix the first four failing tests: we can define functions add(), subtract(), multiply(), divide() in index.js.

Math + Assignment

Additionally, we can increment (++) and decrement (--) a number if it's assigned to a variable:

var number = 5

number++ // 5... hmmmm

number // 6 -- the number was incremented after it was evaluated

number-- // 6

number // 5

We can also put the incrementor and decrementor operations before the number:

--number // 4

++number // 5

But generally, you will see them placed after the number (and we recommend that that's where you put them). If you're interested in the difference, take a look here

And, while we're on the subject, you'll usually only want to use these incrementors and decrementors when the shorthand makes what you're writing easier to read (more on when exactly later). Instead, it's best to use the basic arithmetic operators combined with =. For the examples below, assume that number is equal to 5 (and resets for every example).

  • += modifies the value to the operator's left by adding to it the value to the operator's right:
number += 3 // 8
  • -= modifies the value to the operator's left by subtracting from it the value to the operator's right:
number -= 2 // 3
  • *= modifies the value to the operator's left by multiplying it by the value to the operator's right:
number *= 10 // 50
  • /= modifies the value to the operator's left by dividing it by the value to the operator's right:
number /= 5 // 1

The thing to remember about these methods is that they modify the variable in place. So, if we have two functions that depend on the same external variable, the order in which they are called matters. Follow along in console copying each function and statement below one at a time:

var number = 10

function add5() {
  number += 5
}

function divideBy3() {
  number /= 3
}

divideBy3()

console.log(number) // 3.333333333335

add5()

console.log(number) // 8.333333333335

// reset number
number = 10

add5()

console.log(number) // 15

divideBy3()

console.log(number) // 5

Because these methods are more explicit, we prefer += to ++ and -= to -- (usually).

Okay, now we're ready to write solutions for the next two functions: increment(n) and decrement(n). These methods should take in a number, and either increments the provided value by one or decrements it by one respectively, returning the result.

Parsing Numbers

Sometimes, we'll receive a number — well, we know it's a number, as we've seen many numbers in the past. JavaScript, however, won't know that it's a number because it shows up wrapped in quotes — JavaScript, then, thinks it's a string.

Luckily, JavaScript gives us tools to turn these strings into proper numbers (that is, numbers that JavaScript understands).

parseInt()

The first such tool is the function parseInt(), which accepts two arguments: the value to parse and the base of the value being parsed. Usually you will want to work with base 10, so a typical call to parseInt() looks like

parseInt('2', 10) // 2

What happens if we pass a representation of a non-integer to parseInt()? Let's try it:

parseInt('2.2222', 10)

If we enter the above in console, we will see that parseInt() forces the parsed number to be an integer — which makes sense when we think about it, right?

What happens, though, if we pass utter nonsense to parseInt()? Go ahead and try it in the console — something like

parseInt('nonsense!', 10)

What did it return? NaN? What is that?

NaN stands for "Not a Number" — pretty handy, right? This is the number (in the JavaScript sense) that JavaScript returns when it can't determine a valid value for a numeric operation.

parseFloat()

Above, we saw that parseInt() lops off everything after the decimal point and only returns integers. If we want to preserve decimals, we'll need to use parseFloat().

Unlike parseInt(), parseFloat() accepts only a single argument, the thing to be parsed. We can use it like so:

parseFloat('80.123999') // 80.123999

You're now ready to solve the final two tests in this lab, makeInt(string) and preserveDecimal(string). makeInt(string) should take in a string, parse it into an base 10 integer and return it. preserveDecimal(string) should take in a string, parse it into a float and return it.

Resources

View JavaScript Arithmetic Lab on Learn.co and start learning to code for free.

javascript-arithmetic-lab's People

Contributors

alpha-convert avatar annjohn avatar anthonyntilelli avatar aturkewi avatar edwardgaudio avatar gj avatar hatetank avatar jmburges avatar lizbur10 avatar maxwellbenton avatar pletcher avatar rrcobb avatar sandyvern avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

javascript-arithmetic-lab's Issues

Typos in parseFloat() function statement

Hi, in Introduction to Javascript/ Javascript Arithmetic Lab, there seems to have a TYPO.
It says that: "Unlike parseInt(), parseFloat() accepts only a single argument, the thing to be parsed."
But when i tried parseFloat('2.2.0000000000000000001',10), it returned: 2.2.
Beside, parseFloat() can accept 1 argument two. So I think this function accepts both.

The IDE Lesson Broke

When I click on "Open IDE" it tells me that it can't find the lesson and to check my input.

JavaScript Arithmetic Lab - misleading statement

The lesson states the following under the basic math paragraph ,

"At this point, we can fix the first four broken tests: we can define functions add(), subtract(), multiply(), divide() in index.js."

but the provided index.js file is empty. It looks like the goal is to have students create their own functions. So the above statement should be corrected to indicate that.

makeInt(n) parseInt

For the functions makeInt(n) using parseInt, the test returns NaN even though the string n is parsed.

function makeint(n) { integer = parseInt(n); return integer; }

In console, on browser using the number that was to be expected, after declaring the function, returns the expected value of the test.

Can't pass

I have this code for parseInt and its not passing for base 10. Here's my code
function makeInt(n){
parseInt('n', 10)
return n
}
Any suggestions?

JavaScript Arithmetic Lab - missing test questions

The JavaScript Arithmetic Lab concludes by saying "You're now ready to solve the final two tests in this lab, makeInt(n) and preserveDecimal(n)."

The lab does not specify what the user has to accomplish in makeInt(n) or preserveDecimal(n), nor where the tests should be submitted (I'm assuming index.js).

This bars the user from moving forward--please change to the same format as previous labs.

Learn IDE

Today Learn IDE wont open. I dont know if the problem is on my side or with Learn IDE?

Confused

I am very confused as to what I was supposed to learn. It wanted me to code math equations, however; I don't really think it gave me the proper functions to do so. The "Read Me" ended with saying that we were ready for the next part of the lab, but didn't tell us how to go about it. I failed all of my test and it still allowed me to move on. I am not sure of the purpose of this lesson.

Fork

It will not let me fork the lab.

Add a note on the labs

Can we talk a bit more about this lab at the end?

We don't have to tell them how to do it, but just some more explanation such as you're going to write "three (not sure how many offhand) functions." Use the tests to figure out how to do it.

Also in the index.js file can we just write the list of the functions and then comment in where they should write their code?

@jmburges

Need help on the first one

I'm overthinking this but I can't get it to work...

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

Possible error in the lesson

I ran a learn test on the terminal which reported that the test failed, however the test passed on the website's lesson. I'm not sure whats goign on
rpotp `1

This is the code I used to get this error.
`function add(a,b)
{
return a + b;
}

function subtract(a,b)
{
return a - b;
}

function multiply(a,b)
{
return a * b;
}

funtion divide(a,b)
{
return a / b;
}
`

ReferenceError

I'm receiving a "ReferenceError: add is not defined"

In JavaScript we define a function by denoting it with the keyword "function"

All my functions have been defined:
var number; function add(a, b){ number = a + b; return number; } function subtract(a, b){ number = a - b; return number; } function multiply(a, b){ number = a * b; return number; } function divide(a, b){ number = a / b; return number; } function inc(a){ number = a + 1; return number; } function dec(a){ number = a - 1; return number; } function makeInt(a){ number = parseInt(a, 10); return number; } function preserveDecimal(a){ number = parseFloat(a, 10); return number; }

and I'm still failing the learn test.

Fix the Scope Lab

Hey big thanks in advanced,

I am stuck on the Fix the Scope Lab on the last test. The last lines of my code are as follows:

var theFunk = funkyFunction();
theFunk();

ive tried a lot of other methods but this is my best guess atm. Banging my head against the wall and my tremendous magical abilities have no effect. please help!

-D

Can't figure out hoisting

I've tried everything and can't seem to get how to fix this code:

function crazy() {
// fix the code in here:
thisIsCrazy();
var thisIsCrazy = function(){
console.log("hey!!!")
}
}
I am ONLY supposed to add/edit underneath the comment, correct?

preserveDecimal

Keep getting the error " preserveDecimal(n) preserves n's decimals (it parses n as a floating point number) and returns the parsed number: Error: Expected NaN to be 2.222"

I've entered function preserveDecimal(n) {
return parseFloat('n')
}

Am I missing something obvious?

Clicking "here" doesn't direct to the proper site

"But generally, you will see them placed after the number (and we recommend that that's where you put them). If you're interested in the difference, take a look here"

I tried clicking "here" but instead of reaching http://jsforallof.us/2014/07/10/pre-increment-vs-post-increment I was redirected to http://ww12.jsforallof.us/

IDE Keeps Dropping

screen shot 2018-12-09 at 1 35 55 pm

I have a strong wifi signal, so there's no issue there. I believe it is with the IDE, it keeps disconnecting. This has happened quite often even while trying to complete other modules.

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.