Data types, Variables & Operators Copy

Introduction

JavaScript is one of the most important programming languages. It is definitely the future of the web. More and more of the logic is making its way to the client side in order to facilitate lightning fast user experiences. In addition JavaScript is also moving to the server side with Node.js.

For this reason in this lesson we will dive deep into JavaScript and make sure that by the end of this lesson you have a very good understanding of how it works.

As usual this lesson starts with a look at the basics of JavaScript and continues with more advanced topics.

Learning Objectives

  • Introducing javaScript programming language.
  • Different javascript data types.
  • What is primitive values.
  • What are variables, and how to declare a variable in javaScript?
  • Differences between var, let & const javascript keywords.
  • What do an operator, a method, and expressions concepts mean?
  • javascript different operators(arithmetic,Assignment and Comparison operators).

JavaScript – An Introduction

Let’s get started with this recorded live session

Then visit the web page JavaScript For Cats – An introduction for new programmers and start learning about the basic concepts of JavaScript.

Data Types

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;
/* In the next line we are accessing a variable, but forgot to assign a value to it */
console.log( myEmptyVariable ); 

// 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.

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)

Operators

  1. Numbers (JavaScript.info)

  2. Basic math in JavaScript (MDN)

  3. Basic Math Operators (JavaScript.info)

  4. At this point, it is advised 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.

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!

Leave a Reply