Learn JavaScript  Part  1: Data Types, Variables and Strings

Learn JavaScript Part 1: Data Types, Variables and Strings

Doing a refresher on JavaScript basics is a reality for most developers because learning never stops in software development, especially for beginners who are still learning basic programming concepts.

I created this tutorial for:

  • Absolute beginners in JavaScript. I wrote it in a way that someone learning how to write "Hello World" can understand.
  • People who need to refresh their knowledge on JavaScript basics and are looking for a simple tutorial without unnecessary jargon.

This is a first of several series where I will dive into JavaScript concepts and create learner-friendly content.

To start us off, I explore the basic level of JavaScript; Data types, variables and strings. I've explained the concepts in a simple manner that's easy to understand, especially for newbies in software development. Read along!

Data Types

In Computing, data is information that represents value to a computer and can be translated in a way that's relevant to the computer. This translation converts information into a binary form that a computer can understand. There are 8 data types in JavaScript:

  1. String - A data type that stores textual characters inside a double or single quote
  2. Boolean - A type that represents a true or false value.
  3. Object - An unordered collection of multiple data types or properties known as key value pairs. Note: The key is a string or property name, and value represents anything 4. Null - A primitive data type that represents the absence of value. Only has one value i.e. null.
  4. Undefined - Represents a variable with no value assigned to it.
  5. Bigint (Big Integer) - A data type that represents large integers not assigned a specific value.
  6. Number - A Data type that represents integers and floating points (decimal numbers).
  7. Symbol - A data type used to create identifiers for objects.

Seven of these data types (all except Objects) are primitive data types, meaning, they cannot be changed (are immutable) and do not contain methods or properties.

Variables

Variables allow computers to store data which is then used to perform various activities that produce a specific result. You store this data by using a label to point to the data instead of using the data type as it is.

Variables are similar to the mathematical variables x and y, symbols used to store or represent data, like a placeholder of sorts.

Before ES6, you could declare a variable by placing the keyword var in front of a variable, as seen below:

var Catherine; //correct way to declare a variable

Storing Value in JavaScript

By now, you know how to declare a variable. But what about assigning value or a data type to that variable? Storing or assigning value to a variable is what "activates" a variable so you can use it in your function. You cannot use a variable anywhere If it's not assigned value. So how do you go about it?

You assign value or a data type to a variable with the assignment operator (=). So in our variable example above, it will look like below. We assigned the String value of "my name" to Catherine. You can one variable's value to a new variable. See the example below:

var jane; // declare variable
jane = "first name"; // assign value to the variable above
var doe; //declare another variable with no value
doe = jane; // Then assign the new variable the content of the first variable. In our case, the doe variable has the same value as the jane variable.

Another example below looks like this:

var number; // Declare one variable with no value
number = 7; // assign the value 7 to the first variable
var string; // declare a second variable with no value
string = number; // assign the second variable the value from the first variable. The string variable will now have the same value, 7, as the first variable

Initializing Variables

Initializing a variable means you define a variable and its value simultaneously and in the same scope that it's declared. You are essentially specifying a value to assign to the variable before it's used across your program. You're also condensing the lines of code (see the code we wrote in the previous section) into a compact variable. See the example below:

So instead of writing an undefined variable like this:

var myCar;
myCar = "Toyota";

You now write:

var myCar = "toyota";

Note that variables are case-sensitive. The best practice is to write variables in camelCase, meaning that the first word starts in lowercase, the second word begins in uppercase, and every subsequent name you add to the variable starts in uppercase. For example:

var myCar = "Toyota"
var yourCar = "Audi"
var anotherGoodCar = "BMW"

Uninitialized Variables

In the previous sections, we explained how to initialize a variable. With uninitialized variables, i.e., where you only declare a variable without assigning a value or data type, they automatically have an initial value called "undefined." an uninitialized variable will always return an error when you try to perform an operation on it.

For example, If you perform a mathematical operation on an undefined variable, you will get a NaN error (Not a Number). If you concatenate a string with an undefined variable, you'll still get an "undefined" error.

Another example is is you try to execute an operation on an uninitialized/undefined constant (read about constants in the section below), you'll get the error below:

const Catherine;
console.log("Catherine".length);
// Catherine is not defined

Understanding this concept is crucial in writing clean code and debug faster whenever you encounter errors in your code.

Declaring Variables- The Difference Between Var, Let, and Const

If you've noticed, we've been declaring most variables with the "var" keyword. This was a convention used before ES6 was released. ES6, also known as ECMAScript 2015, was a significant JavaScript update released in 2015. This update marked a significant revision to most JavaScript features, one of them being how we declare variables. Before 2015, we'd declare variables with the var keyword, but with the ES6 update, we got these new keywords; let and const. But why the change? After all, the var keyword seems to be working well in the previous section of this blog.

While it's not criminal to use var, it's best practice to avoid using this keyword because it creates more complexity and bugs as your code base grows. To understand why the var keyword is problematic, you need to understand a phenomenon called scope. Understanding scope will also help you know the difference between var, let, and const.

The Google dictionary definition for scope is "the extent of the area or subject matter that something deals with." Synonyms for scope include range, extent, width, breadth, area, or horizon.

So in JavaScript, scope is defined as the current context, area, range, or extent that values and expressions are visible to variables for execution. Scope determines how you access variables across your code base. Scope can also be defined as the availability of variables and functions across various parts of your code: There are three scopes in JavaScript:

  1. Global scope - variables that are declared outside a function. You can access and change global variables outside a function and in any scope.

  2. Local (function) scope - Variables declared within a function cannot be accessed outside of it. Since they cannot be accessed or changed by another function,you can use or invoke the same variable elsewhere in your program. You can use the same variable to create a new function or scope.

  3. Block scope - This is another feature introduced in ES6. Block scope restricts a variable to the block it's declared in and cannot be accessed outside the block. NOTE: a block is code bounded within curly braces {}.

Variables using the var keyword can be accessed at a global or local scope. You can declare the same variable elsewhere or accidentally use it in a different scope and redefine the original function that used the same var keyword.

And because JavaScript does not throw an error when you declare the same variable more than once with the var keyword, it is difficult to identify and fix bugs in your program, which will show up when you compile your code. Do you now see why the var keyword is problematic?

So what is the next best solution? Well, ES6 introduced block scope that's facilitated by the let and const keywords - to solve the issue with the var keyword.

The const keyword, derived from the word constant, defines constant values that cannot change. Any value defined by the const keyword cannot be re-declared or updated and stays the same within the global, local, and block scope.

On the other hand, the let keyword defines variables that cannot be re-declared within a block scope BUT can be updated within its block scope.

From the definitions above, you can now see why the ES6 update to keywords was necessary because now, with the let and const keywords, you're able to bind code to their blocks without the risk of mixing up variables and creating errors in your program.

Let's use a practical example by declaring the same variable twice with the var and const keywords:

var myLocation = "Nairobi";
var myLocation = "Kisumu";


console.log (myLocation);
// You'll get Kisumu because both variables can still be accessed, despite declaring them twice. So JavaScript will not throw an error but will still create bugs in your code.
let myLocation = "Nairobi";
let myLocation = "Kisumu";

console.log (myLocation);

//You will get this error "Cannot re-declare block-scoped variable 'myLocation'"

Strings

In the code example above, we declared and initialized a string variable. This means that we enclosed the value or data type in double or single quotes ('' or ""). So "my name" is a string literal, a sequence of zero or more characters enclosed in single or double quotes.

Apart from string literals, we also have template literals that are encapsulated with backticks (``) instead of single or double quotes. The ES6 update introduced template literals to replace escape characters. Though you can still use escape characters, template literals help write cleaner code and enable you to work with multiline strings.

var welcome = 'Hello, \'my name\' is Catherine' // Example with escape characters
var welcome = "Hello, `my first name is Catherine" //example with template literals

Here's an example of a multiline string with template literals:

var welcome = `This is my name. I live in Kenya
 and I love to code`;

String Interpolation

Suppose you had enclosed the multiline string above with single or double quotes. In that case, you'd have gotten an "Invalid or unexpected token" error hence why we use template literals for multiline strings. Template literals also came with the ES6 update.

Interpolate is a verb that means to insert, add, embed, or introduce something. So string interpolation means to add or insert an expression, variable or different data type into a string. You're essentially adding other things into a string, without changing the essence of that string.

Template literals help you increase the functionality of a string. You can insert variables, expressions, or values into a string. The syntax for string interpolation looks like this:

A template literal (``) followed the string, a dollar sign ($), and curly brackets with the expression in it.

String ${expression, variable or value}

Here's a practical example: */

const name = "Catherine";
const country = "Kenya";
let role = "software developer";
let location = "Nairobi";
console.log (`Hello, I am ${name}, a ${role} in ${country}. I reside in ${location}.`)
Result: Hello, I am Catherine, a software developer in Kenya. I reside in Nairobi.

Adding Quotes within a String

There are scenarios where you'll need to add a string within another string whenever you need to fulfill specific criteria, like in a Find method and SQL strings.

Add the forward slash to escape and isolate a string, followed by the quote marks encapsulating the string you want to isolate.

const myTasks = "John went to the market \"and bought shoes\""
console.log (myTasks)
// Result - John went to the market "and bought shoes"

The example above is just one way to manipulate characters like quotation marks within a string.

Escaping characters in Strings

We use escape sequences to manipulate strings and extend string functionality without throwing errors. This is achieved by turning special characters into strings by using a backslash, followed by the symbol representing the operation you want to execute.

Types of Escape Sequences (With Examples):

  • \'\' - adds single quotes to a section of a string. This also works the same way with double quotes.

const myString = "Mary went to the shop.\'I bought bread and milk\', she said."
console.log (myString);
// Mary went to the shop.'I bought bread and milk', she said.
  • \n - This creates a new line in a string.

const myString = "Mary went to the shop.\nShe came back with bread and milk"
console.log (myString);
`Mary went to the shop.
She came back with bread and milk`
  • \r - This terminates a section of a string that comes before the escape sequence

const myString = "Mary went to the shop.\rShe bought bread and milk"
console.log (myString);
//She bought bread and milk
  • \t - adds indentation or spacing in a string

const myString = "Mary went to the shop.\tShe bought bread and milk"
console.log (myString);
// Mary went to the shop.  She bought bread and milk

In the next article, I will continue with part 2 on JavaScript concepts you need to learn in order to build you foundation before moving to more complex areas of JavaScript.