Developer Tools: Part 2

Introduction

As already stated before it is an essential skill for every developer to know how to use the developer tools. These tools are very useful because they save the developers a lot of time. They can be used to run JavaScript code, to edit HTML and CSS styles without having to refresh the page and much more.

So far you should be familiar using the developer tools for debugging in HTML and CSS so now it is time to see how we can use them in JavaScript.

Getting Started with Dev Tools

In order to use the developer tools we need to open the Developer Tools menu. There are three ways to do that:

  1. From the Browser Menu:
    • Chrome: Select the Chrome Menu > More Tools > Developer Tools
    • Firefox: Select the Firefox Menu > Web Developer> Toggle Tools
  2. Right click anywhere on a webpage and select Inspect
  3. Use the keyboard shortcut F12 or CTRL + Shift + I (option + command + I on Mac)

Hands-on

1.Watch this introductory video by The Net Ninja on using the JavaScript Console.

Duration: 5 minutes

  1. Watch the first 33 minutes of this in-depth video by Traversy Media and learn all about the powerful tools available through in Chrome’s Developer Tools

Duration: 34 minutes (The video is set to stop at 33:35)

https://www.youtube.com/embed/x4q86IjJFag?start=0&end=2013

  1. Go to the Chrome DevTools Documentation by Google. The following subsections cover what you’ll be using the Developer Tools for 95% of the time. Feel free to skip the elements you are already familiar with:

    • Open DevTools
    • CSS
      1. Get Started with Viewing and Changing CSS
      2. CSS Reference
    • Console
      1. Overview
    • Mobile Simulation
      1. Overview
    • DOM
      1. Get Started
    • JavaScript
      1. Get Started
      2. Pause Your Code With Breakpoints
  2. After becoming familiar with the Chrome DevTools, install and open up Mozilla FireFox check and compare the Developer tools. You must familiarize yourself with at least 3 browsers and their Developer tools in order to be able to debug browser-specific issues.

Additional Resources

In this section you can find a lot of helpful links to other content. This is a supplemental material for you if you want to dive deeper into some concepts.

  1. In this tutorial you will learn 14 Chrome dev tools tips and tricks JavaScript 30 Video by Wes Bos.

Duration: 10 minutes

Assignment

  • Use Loom or another screen recording software to record a small video (5 minutes max) in which you’ll demonstrate and describe the following DevTools capabilities:
    • Open up the DevTools
    • Switch to Mobile/Tablet View
    • Check/Uncheck (toggle) some CSS properties
    • Change the (text) content of some Element
    • Add/remove CSS classes from an element
    • Delete an element
    • Copy/Paste an element somewhere in the HTML
    • Force the :hover state on an element
    • Use the color picker to change either the color or background-color of an element
    • Modify some CSS rule’s pixel values using the keys
    • Find the width, margin, border and padding of an element’s Box model using the Computed panel
    • Get a reference to an HTML element in JavaScript ($0)
    • Run some console assertions

Record your video, add the URL in a text file named devtools-part2-screencast.txt and upload it in the Assignment panel below. In case you use some other kind of recording software, upload the file in Google Drive or DropBox, share the video link and add the relevant URL in the text file.


The archived old version of this post can be found here

UPDATED: 03.06.2021

LOOKING FOR HELP?

When looking for help, try doing so in the following order:

  • Did you try everything you could?
  • Did you read the documentation?
  • Did you Google for it?
  • Did you post your question on Slack/Forum?
  • Did you ask your fellow students for help?
  • Did you ask your Mentors for help?
  • Did you leave a comment on the comments section of this page?
  • Did you ask your Instructor for help?
    • Did you arrange and appointment with your instructor using Calendly? Visit this URL and set up an appointment: https://calendly.com/kostasx
    • Is it urgent? Did you try reaching him on Slack

Fundamentals: Part 2

Introduction

In JavaScript you will encounter the different types of data. Some of them are very common and these lessons will help you build a strong foundation in all of them. Therefore it is essential to read this article JavaScript Data Types to get a quick idea of the most common data types.

Estimated reading and practice time: approx. 1 hour


Some notes regarding the undefined and null values

undefined: Can be thought of as a value used for unintentionally missing values, for example declared variables with no values assigned to them:

let myEmptyVariable;

console.log( myEmptyVariable ); // We are accessing a variable, but forgot to assign a value to it

// undefined

Remember, that the language specification states that:

undefined is used when a variable has not been assigned a value

You will also find undefined when trying to access Object properties that have not been created (more on this on the next lessons) and on Function parameters that have not been assigned a value (also, more on this later).

null: Can be used for intentionally missing values.

Here’s how the language specification describes null:

null represents the intentional absence of any object value

Unfortunately, JavaScript (still) thinks that the typeof null is object, so be careful when you are trying to detect the type of a value.

Live Sessions

Watch the following 3 videos of the recorded live sessions (29/10/2020) that introduce various JS concepts such as Primitive data types, conditionals, arrays and more.

Don’t forget to pause the video and practice on the concepts presented.

Part 1/3 – Duration: 88 minutes

Part 2/3 – Duration: 96 minutes

Part 3/3 – Duration: 64 minutes

Do you have any questions regarding the concepts and code presented in the videos? Leave your questions and comments on the comments section at the bottom of the page.

Learning Objectives

  • Understand the eight data types of javascript
  • Understand the primitive and the not primitive data types
  • Describe the difference between single, double, and backtick quotes for strings
  • Understand which type of quote lets you embed variables/expressions into a string
  • Describe how to embed variables/expressions into a string
  • Describe how to escape characters in a string
  • Describe the difference between slice/substring/substr
  • Explain what methods are
  • Explain the three logical operators
  • Explain the comparison operators
  • Explain what nesting is
  • Explain the truthy and falsy values.
  • Explain the falsy values in Javascript
  • Explain the syntax for an if/else conditional
  • Explain the syntax for a switch statement
  • Explain the syntax for a ternary operator
  • Explain the relationship between null and undefined
  • Explain what conditionals are

Study: Strings

Strings, likewise numbers, are very important data types in JavaScript. A string is simply a piece of text… and is a fundamental building block of the language.

  1. Read and code along with yet another MDN tutorial on the topic: Handling text — strings in JavaScript. (Dedicate at least 90 minutes on this material)

  2. Go through this lesson: JavaScript String Methods to learn more about what you can do with strings… be sure to do the exercises at the end! Suggested reading and coding time for this material: 90 minutes After reading this post, you must ensure that you have a firm understanding of the following String properties and methods:

  • The .length property
  • The following String methods:
    • indexOf()
    • lastIndexOf()
    • search()
    • slice()
    • substring()
    • substr()
    • replace()
    • RegEx
    • toLowerCase()
    • toUpperCase()
    • concat()
    • trim()
    • charAt()
    • charCodeAt()
    • split()
  1. Let’s now learn what a method is: a method is a bit of functionality that is built into the language or into specific data types. In the previous W3Schools exercise, you learned a few methods that can be used on strings, such as indexOf and search. However there a lot more methods that can be use on strings. An exhaustive list can be found here: String methods.

Study: Conditionals

Up until now we haven’t done much with our programming. We have told the computer to do some math but the the essence of programming is teaching the computer how to make decisions. In other words we need to tell the computer when to do certain things. And the way we do it is with the conditionals.

So now it is time to have fun!

  1. The first step in learning about conditionals is making sure you understand comparisons: JavaScript.info – Comparisons. (Estimated reading and coding time for this material: approx. 1 to 2 hours

  2. JavaScript if, else and else if you will get a first glance at conditionals in JavaScript. (Dedicate at least 1 hour on this material)

  3. Logical Operators you will learn about logical operators. (Dedicate at least 1 hour on this material)

  4. Making decisions in your code — conditionals provides several interesting examples of how you could use it building websites. (Estimated reading, practice time and completion of exercises: approx. 10 hours)

Supplementary Material:

  1. Conditional branching: if, ‘?’ covers the same basic concept (read through it as a review!) Furthermore it offers the usual ‘tasks’ at the bottom of the page!

  2. How To Use the Switch Statement in JavaScript will teach you about the switch statement.

BOOKMARK THIS: This last resource has been created by Tania Rascia. Tania is one of the best online educators when it comes to Frontend and web technologies, so make sure to follow here on twitter, join her newsletter and definitely bookmark her website which contains a lot of amazing tutorials and posts. Whenever you find yourself troubled or tangled up in a difficult concept, search Tania’s posts and tutorials for it. Chances are, you will find yourself a clear explanation.

Time for Practice

In order to give you more practice and more exercises to play with we have created ome repl.it exercises.

Make sure that you do the exercises in the given order.

Instructions: Pressing run at the top will run the code. Read all directions, watch the terminal, and read all the errors. Don’t forget to use console.log extensively.

Make sure that you save your solutions as you will be asked to work on them later on in the course. Also, you will need to create an account at repl.it and fork the exercises in order to complete them.

Additional Resources

In this section you can find a lot of helpful links to other content. This is a supplemental material for you if you want to dive deeper into some concepts.

  • Take a 10 to 15 minutes break and watch The Net Ninja’s Regular Expressions Tutorial. Don’t worry if you feel overwhelmed by the concept of Regular Expressions as it’s one of the most difficult and awkward computer languages. All that we want at this point, is for you to gain some basic understanding of how this pattern matching language works and become familiar with this undeniably powerful feature of most programming languages.

  • If you feel comfortable, continue to this site and practice yourself with some easy to medium pattern matching tasks.

Estimated viewing and coding practice time: approx. 3 to hours

References

Assignment

Follow the instructions at the GitHub Repository and submit your Pull Request URLs.


The archived old version of this post can be found here

UPDATED: 03.06.2021

Contributors

LOOKING FOR HELP?

When looking for help, try doing so in the following order:

  • Did you try everything you could?
  • Did you read the documentation?
  • Did you Google for it?
  • Did you post your question on Slack/Forum?
  • Did you ask your fellow students for help?
  • Did you ask your Mentors for help?
  • Did you leave a comment on the comments section of this page?
  • Did you ask your Instructor for help?
    • Did you arrange and appointment with your instructor using Calendly? Visit this URL and set up an appointment: https://calendly.com/kostasx
    • Is it urgent? Did you try reaching him on Slack

Fundamentals: Part 1

Learning Objectives

  • Declaring variables in JavaScript
  • Naming variables
  • Operations, Operators and Operands in JavaScript
  • Operator Precedence
  • Using the + Operator with Numbers and Strings
  • Strict and Abstract Equality Operators
  • The increment++ and decrement– operators
  • The assignment operators

Live Session

Watch the following 3 parts of the recording of the live session (21/10/2020) that introduces JavaScript:

Total duration: 175 minutes

Part 1/3 – Duration: 68 minutes

Part 2/3 – Duration: 90 minutes

Part 3/3 – Duration: 14 minutes

Numbers

Computers initially were humans calculating numbers and gradually evolved into the digital machines we use every single day. Nowadays, we can hardly thing of a computer program that does not involve numbers and numeric calculations. Calculating tax revenue, stock prices or the movement of a spaceship in a computer game, all involve work with numbers.

JavaScript is able to operate on any type of number (integers, floating point numbers, negative numbers, fractions, etc.) and also provides a multitude of useful Math constants (PI, E, etc.) and methods to work on these numbers: calculating the sine/cosine or the square root of a number, rounding a floating point number or getting a random number and much, much more.

In order to comprehend how numbers work and are handled by JavaScript, you must thoroughly study the following Numbers in JavaScript section and all subsequent resources and implement the concepts in your web pages.

The following section comes from the book You Don't Know JS by Kyle Simpson. It is one of the best and most detailed guides to the Number type in JavaScript.

Numbers in JavaScript

JavaScript has just one numeric type: number. This type includes both "integer" values and fractional decimal numbers. I say "integer" in quotes because it’s long been a criticism of JS that there are not true integers, as there are in other languages. That may change at some point in the future, but for now, we just have numbers for everything.

So, in JS, an "integer" is just a value that has no fractional decimal value. That is, 42.0 is as much an "integer" as 42.

Like most modern languages, including practically all scripting languages, the implementation of JavaScript’s numbers is based on the "IEEE 754" standard, often called "floating-point." JavaScript specifically uses the "double precision" format (aka "64-bit binary") of the standard.

There are many great write-ups on the Web about the nitty-gritty details of how binary floating-point numbers are stored in memory, and the implications of those choices. Because understanding bit patterns in memory is not strictly necessary to understand how to correctly use numbers in JS, we’ll leave it as an exercise for the interested reader if you’d like to dig further into IEEE 754 details.

Numeric Syntax

Number literals are expressed in JavaScript generally as base-10 decimal literals. For example:

var a = 42;
var b = 42.3;

The leading portion of a decimal value, if 0, is optional:

var a = 0.42;
var b = .42;

Similarly, the trailing portion (the fractional) of a decimal value after the ., if 0, is optional:

var a = 42.0;
var b = 42.;

Warning: 42. is pretty uncommon, and probably not a great idea if you’re trying to avoid confusion when other people read your code. But it is, nevertheless, valid.

By default, most numbers will be outputted as base-10 decimals, with trailing fractional 0s removed. So:

var a = 42.300;
var b = 42.0;

a; // 42.3
b; // 42

Very large or very small numbers will by default be outputted in exponent form, the same as the output of the toExponential() method, like:

var a = 5E10;
a;					// 50000000000
a.toExponential();	// "5e+10"

var b = a * a;
b;					// 2.5e+21

var c = 1 / a;
c;					// 2e-11

Because number values can be boxed with the Number object wrapper (see Chapter 3), number values can access methods that are built into the Number.prototype (see Chapter 3). For example, the toFixed(..) method allows you to specify how many fractional decimal places you’d like the value to be represented with:

var a = 42.59;

a.toFixed( 0 ); // "43"
a.toFixed( 1 ); // "42.6"
a.toFixed( 2 ); // "42.59"
a.toFixed( 3 ); // "42.590"
a.toFixed( 4 ); // "42.5900"

Notice that the output is actually a string representation of the number, and that the value is 0-padded on the right-hand side if you ask for more decimals than the value holds.

toPrecision(..) is similar, but specifies how many significant digits should be used to represent the value:

var a = 42.59;

a.toPrecision( 1 ); // "4e+1"
a.toPrecision( 2 ); // "43"
a.toPrecision( 3 ); // "42.6"
a.toPrecision( 4 ); // "42.59"
a.toPrecision( 5 ); // "42.590"
a.toPrecision( 6 ); // "42.5900"

You don’t have to use a variable with the value in it to access these methods; you can access these methods directly on number literals. But you have to be careful with the . operator. Since . is a valid numeric character, it will first be interpreted as part of the number literal, if possible, instead of being interpreted as a property accessor.

// invalid syntax:
42.toFixed( 3 );	// SyntaxError

// these are all valid:
(42).toFixed( 3 );	// "42.000"
0.42.toFixed( 3 );	// "0.420"
42..toFixed( 3 );	// "42.000"

42.toFixed(3) is invalid syntax, because the . is swallowed up as part of the 42. literal (which is valid — see above!), and so then there’s no . property operator present to make the .toFixed access.

42..toFixed(3) works because the first . is part of the number and the second . is the property operator. But it probably looks strange, and indeed it’s very rare to see something like that in actual JavaScript code. In fact, it’s pretty uncommon to access methods directly on any of the primitive values. Uncommon doesn’t mean bad or wrong.

Note: There are libraries that extend the built-in Number.prototype (see Chapter 3) to provide extra operations on/with numbers, and so in those cases, it’s perfectly valid to use something like 10..makeItRain() to set off a 10-second money raining animation, or something else silly like that.

This is also technically valid (notice the space):

42 .toFixed(3); // "42.000"

However, with the number literal specifically, this is particularly confusing coding style and will serve no other purpose but to confuse other developers (and your future self). Avoid it.

numbers can also be specified in exponent form, which is common when representing larger numbers, such as:

var onethousand = 1E3;						// means 1 * 10^3
var onemilliononehundredthousand = 1.1E6;	// means 1.1 * 10^6

number literals can also be expressed in other bases, like binary, octal, and hexadecimal.

These formats work in current versions of JavaScript:

0xf3; // hexadecimal for: 243
0Xf3; // ditto

0363; // octal for: 243

Note: Starting with ES6 + strict mode, the 0363 form of octal literals is no longer allowed (see below for the new form). The 0363 form is still allowed in non-strict mode, but you should stop using it anyway, to be future-friendly (and because you should be using strict mode by now!).

As of ES6, the following new forms are also valid:

0o363;		// octal for: 243
0O363;		// ditto

0b11110011;	// binary for: 243
0B11110011; // ditto

Please do your fellow developers a favor: never use the 0O363 form. 0 next to capital O is just asking for confusion. Always use the lowercase predicates 0x, 0b, and 0o.

Small Decimal Values

The most (in)famous side effect of using binary floating-point numbers (which, remember, is true of all languages that use IEEE 754 — not just JavaScript as many assume/pretend) is:

0.1 + 0.2 === 0.3; // false

Mathematically, we know that statement should be true. Why is it false?

Simply put, the representations for 0.1 and 0.2 in binary floating-point are not exact, so when they are added, the result is not exactly 0.3. It’s really close: 0.30000000000000004, but if your comparison fails, "close" is irrelevant.

Note: Should JavaScript switch to a different number implementation that has exact representations for all values? Some think so. There have been many alternatives presented over the years. None of them have been accepted yet, and perhaps never will. As easy as it may seem to just wave a hand and say, "fix that bug already!", it’s not nearly that easy. If it were, it most definitely would have been changed a long time ago.

Now, the question is, if some numbers can’t be trusted to be exact, does that mean we can’t use numbers at all? Of course not.

There are some applications where you need to be more careful, especially when dealing with fractional decimal values. There are also plenty of (maybe most?) applications that only deal with whole numbers ("integers"), and moreover, only deal with numbers in the millions or trillions at maximum. These applications have been, and always will be, perfectly safe to use numeric operations in JS.

What if we did need to compare two numbers, like 0.1 + 0.2 to 0.3, knowing that the simple equality test fails?

The most commonly accepted practice is to use a tiny "rounding error" value as the tolerance for comparison. This tiny value is often called "machine epsilon," which is commonly 2^-52 (2.220446049250313e-16) for the kind of numbers in JavaScript.

As of ES6, Number.EPSILON is predefined with this tolerance value, so you’d want to use it, but you can safely polyfill the definition for pre-ES6:

if (!Number.EPSILON) {
	Number.EPSILON = Math.pow(2,-52);
}

We can use this Number.EPSILON to compare two numbers for "equality" (within the rounding error tolerance):

function numbersCloseEnoughToEqual(n1,n2) {
	return Math.abs( n1 - n2 ) < Number.EPSILON;
}

var a = 0.1 + 0.2;
var b = 0.3;

numbersCloseEnoughToEqual( a, b );					// true
numbersCloseEnoughToEqual( 0.0000001, 0.0000002 );	// false

The maximum floating-point value that can be represented is roughly 1.798e+308 (which is really, really, really huge!), predefined for you as Number.MAX_VALUE. On the small end, Number.MIN_VALUE is roughly 5e-324, which isn’t negative but is really close to zero!

Safe Integer Ranges

Because of how numbers are represented, there is a range of "safe" values for the whole number "integers", and it’s significantly less than Number.MAX_VALUE.

The maximum integer that can "safely" be represented (that is, there’s a guarantee that the requested value is actually representable unambiguously) is 2^53 - 1, which is 9007199254740991. If you insert your commas, you’ll see that this is just over 9 quadrillion. So that’s pretty darn big for numbers to range up to.

This value is actually automatically predefined in ES6, as Number.MAX_SAFE_INTEGER. Unsurprisingly, there’s a minimum value, -9007199254740991, and it’s defined in ES6 as Number.MIN_SAFE_INTEGER.

The main way that JS programs are confronted with dealing with such large numbers is when dealing with 64-bit IDs from databases, etc. 64-bit numbers cannot be represented accurately with the number type, so must be stored in (and transmitted to/from) JavaScript using string representation.

Numeric operations on such large ID number values (besides comparison, which will be fine with strings) aren’t all that common, thankfully. But if you do need to perform math on these very large values, for now you’ll need to use a big number utility. Big numbers may get official support in a future version of JavaScript.

Testing for Integers

To test if a value is an integer, you can use the ES6-specified Number.isInteger(..):

Number.isInteger( 42 );		// true
Number.isInteger( 42.000 );	// true
Number.isInteger( 42.3 );	// false

To test if a value is a safe integer, use the ES6-specified Number.isSafeInteger(..):

Number.isSafeInteger( Number.MAX_SAFE_INTEGER );	// true
Number.isSafeInteger( Math.pow( 2, 53 ) );			// false
Number.isSafeInteger( Math.pow( 2, 53 ) - 1 );		// true

32-bit (Signed) Integers

While integers can range up to roughly 9 quadrillion safely (53 bits), there are some numeric operations (like the bitwise operators) that are only defined for 32-bit numbers, so the "safe range" for numbers used in that way must be much smaller.

The range then is Math.pow(-2,31) (-2147483648, about -2.1 billion) up to Math.pow(2,31)-1 (2147483647, about +2.1 billion).

To force a number value in a to a 32-bit signed integer value, use a | 0. This works because the | bitwise operator only works for 32-bit integer values (meaning it can only pay attention to 32 bits and any other bits will be lost). Then, "or’ing" with zero is essentially a no-op bitwise speaking.

Note: Certain special values (which we will cover in the next section) such as NaN and Infinity are not "32-bit safe," in that those values when passed to a bitwise operator will pass through the abstract operation ToInt32 (see Chapter 4) and become simply the +0 value for the purpose of that bitwise operation.

Study Guide

  1. Numbers (JavaScript.info)

  2. Basic math in JavaScript (MDN)

  3. Basic Math Operators (JavaScript.info)

  4. What Every JavaScript Developer Should Know About Floating Points

  5. At this point, it is adviced that you read the following article which will provide some insights on how to approach programming problems and challenges. How to think like a programmer — lessons in problem solving. You will go over this article again in one of the upcoming projects.

Variables

Variables are pointers to "storage containers" for data in your code. You can think of variables as something close to your contacts in your mobile phone. Each contact list entry contains a name, e.g. Mary. This is your variable name. And each contact list name (variable name) points to a place in the memory of your mobile phone that stores a telephone number or address, e.g. 6985252114.

VARIABLE NAME POINTER TO DATA IN MEMORY
Mary — Points to –> 6985252114
Ahmed — Points to –> 6971234567

In much the same way, variables in programming languages, are names that point to some memory location in which some kind of data is stored:

var someVariableName = "Just some text.";
// The someVariableName, now points to a place in memory
// where the "Just some text." data is stored and can be retrieved.

Until recently there was only one way to create a variable in JavaScript — the var statement. But in the newest JavaScript versions we have two more ways — let and const.

Take a break and then study the following tutorial about variables from JavaScript.info that explains variables in detail and also contains a Tasks section where you can (must) practice all the concepts that you’ve learned.

The estimated reading and practice time for this material is approximately 2 hours.

Here is a list of the concepts you’ll be introduced to through this post:

  • What is a variable?
  • Constants
  • Variable naming and naming things right
  • Case sensitivity and reserved names

The above tutorial mentioned this, but it’s important enough to note again: let and const are both relatively new ways to declare variables in JavaScript. In many tutorials (and code) across the internet you’re likely to encounter var statements. Don’t let it bother you! There’s nothing inherently wrong with var, and in most cases var and let behave the same way. But sometimes the behavior of var is not what you would expect. Just stick to let (and const) for now. The precise differences between var and let will be explained later. (Source: The Odin Project)

Practice!

Let’s practice those programming skills with some JavaScript code that runs on an HTML file. Create an HTML file and place the JS code inside the script tag.

<!DOCTYPE html>
<html>
    <head>
        <title>Numbers in JavaScript</title>
        <meta charset="UTF-8"/>
    </head>
    <body>
        <script>
            // Your code here:
            console.log("Hello, World!")
        </script>
    </body>
</html>

Save the HTML file in a folder, add the folder in a new VSCode workspace and launch the web page in the browser using the LiveServer VSCode extension. By right-clicking on the web page you can select Inspect or Inspect Element and be able to watch the output on the Developer Tools console. The console.log() command will display any value you place inside the parentheses in the browser’s console and this is a command you’ll be using on a daily basis.

Try to complete the following steps:

Basic Numeric Operations:

  1. Add 2 numbers together! (just type console.log(23 + 97) into your html file)
  2. Add a sequence of 6 different numbers together.
  3. Print the solution to the following equation: (4 + 6 + 9) / 77
    1. answer should be approximately 0.24675
  4. Let’s use variables!
    1. Type the following at the top of the script tag: let a = 10
    2. console.log(a) should print 10
    3. Try the following: 9 * a
    4. and this: let b = 7 * a (returns undefined) and then console.log(b)
  5. You should be getting the hang of this by now… try this sequence:
    1. Declare a constant variable max with the value 57
    2. Set another variable actual to max - 13
    3. Set another variable percentage to actual / max
    4. If you type percentage in the console and press enter you should see a value like 0.7719
  6. Can you think of any real-life scenarios where Numbers and the arithmetic operators of JavaScript can be of use? Take the time to implement these scenarios in your code and add them to the web page. Here’s an example to get you started:

Savings Account:

  1. Create a variable named balance and assign an amount to it. (Think of this as a bank deposit transaction)

  2. Create a variable named yearly_interest and set the value to 0.05. This amounts for a 5% interest rate on a yearly basis for a savings account.

  3. Calculate the balance after 2 years and also after 4 years.

  4. Validate your results against these two online calculators: Savings Calculator / Simple Savings Calculator.

Calculate Grade Average:

  1. Given the grades of students A and B, below, calculate their averages and create as many useful variables as you think:
const studentA_history   = 6;
const studentA_math      = 7;
const studentA_geography = 5;
const studentA_art       = 8;
const studentA_physics   = 4;
const studentA_chemistry = 7;

const studentB_history   = 4;
const studentB_math      = 9;
const studentB_geography = 5;
const studentB_art       = 5;
const studentB_physics   = 6;
const studentB_chemistry = 4;

How about using JavaScript to calculate the VAT (or some other kind of tax) for a product?

const VAT = 24;    // VAT Tax is set to 24%
const smartphone = 300; // Net price
const total = smartphone + ( smartphone * ( VAT / 100 ) ); // Total === net price + VAT

How about using JavaScript to calculate the number of calories burned while walking or any other activity?

How about calculating a woman’s fertile window?

Blood alcohol content anyone?

There is no shortage of (really useful) ideas to implement in JavaScript using Numbers and the arithmetic operators, so let’s get to work!

Additional Resources

In this section you can find a lot of helpful links to other content. This is a supplemental material for you if you want to dive deeper into some concepts.

Assignment

Click this link and follow the instructions on how to complete and submit this assignment.


The archived old version of this post can be found here

UPDATED: 03.06.2021

  • [16.11.2020] Added article for variable shadowing
  • [27.11.2020] Added the bitwise operator rounding trick

CONTRIBUTORS:

LOOKING FOR HELP?

When looking for help, try doing so in the following order:

  • Did you try everything you could?
  • Did you read the documentation?
  • Did you Google for it?
  • Did you post your question on Slack/Forum?
  • Did you ask your fellow students for help?
  • Did you ask your Mentors for help?
  • Did you leave a comment on the comments section of this page?
  • Did you ask your Instructor for help?
    • Did you arrange and appointment with your instructor using Calendly? Visit this URL and set up an appointment: https://calendly.com/kostasx
    • Is it urgent? Did you try reaching him on Slack